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
//------------------------------------------------------------------------------ // <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 bertozzi.mattia.Gatto._4H.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.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; } } } }
34.83871
151
0.584259
[ "MIT" ]
Rimac48/bertozzi.mattia.Gatto.4H
bertozzi.mattia.Gatto.4H/Properties/Settings.Designer.cs
1,082
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Threading.Tasks; using Newtonsoft.Json; namespace CloudStack.Net { public class UpgradeRouterTemplateRequest : APIRequest { public UpgradeRouterTemplateRequest() : base("upgradeRouterTemplate") {} /// <summary> /// upgrades all routers owned by the specified account /// </summary> public string Account { get { return GetParameterValue<string>(nameof(Account).ToLower()); } set { SetParameterValue(nameof(Account).ToLower(), value); } } /// <summary> /// upgrades all routers within the specified cluster /// </summary> public Guid? ClusterId { get { return GetParameterValue<Guid?>(nameof(ClusterId).ToLower()); } set { SetParameterValue(nameof(ClusterId).ToLower(), value); } } /// <summary> /// upgrades all routers owned by the specified domain /// </summary> public Guid? DomainId { get { return GetParameterValue<Guid?>(nameof(DomainId).ToLower()); } set { SetParameterValue(nameof(DomainId).ToLower(), value); } } /// <summary> /// upgrades router with the specified Id /// </summary> public Guid? Id { get { return GetParameterValue<Guid?>(nameof(Id).ToLower()); } set { SetParameterValue(nameof(Id).ToLower(), value); } } /// <summary> /// upgrades all routers within the specified pod /// </summary> public Guid? PodId { get { return GetParameterValue<Guid?>(nameof(PodId).ToLower()); } set { SetParameterValue(nameof(PodId).ToLower(), value); } } /// <summary> /// upgrades all routers within the specified zone /// </summary> public Guid? ZoneId { get { return GetParameterValue<Guid?>(nameof(ZoneId).ToLower()); } set { SetParameterValue(nameof(ZoneId).ToLower(), value); } } } /// <summary> /// Upgrades router to use newer template /// </summary> public partial interface ICloudStackAPIClient { BaseResponse UpgradeRouterTemplate(UpgradeRouterTemplateRequest request); Task<BaseResponse> UpgradeRouterTemplateAsync(UpgradeRouterTemplateRequest request); } public partial class CloudStackAPIClient : ICloudStackAPIClient { public BaseResponse UpgradeRouterTemplate(UpgradeRouterTemplateRequest request) => Proxy.Request<BaseResponse>(request); public Task<BaseResponse> UpgradeRouterTemplateAsync(UpgradeRouterTemplateRequest request) => Proxy.RequestAsync<BaseResponse>(request); } }
36.565789
144
0.628643
[ "Apache-2.0" ]
chaeschpi/cloudstack.net
src/CloudStack.Net/Generated/UpgradeRouterTemplate.cs
2,779
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Aiven.Inputs { public sealed class GetGrafanaGrafanaUserConfigSmtpServerArgs : Pulumi.InvokeArgs { /// <summary> /// Address used for sending emails /// </summary> [Input("fromAddress")] public string? FromAddress { get; set; } /// <summary> /// Name used in outgoing emails, defaults to Grafana /// </summary> [Input("fromName")] public string? FromName { get; set; } /// <summary> /// Server hostname or IP /// </summary> [Input("host")] public string? Host { get; set; } /// <summary> /// Password for SMTP authentication /// </summary> [Input("password")] public string? Password { get; set; } /// <summary> /// SMTP server port /// </summary> [Input("port")] public string? Port { get; set; } /// <summary> /// Skip verifying server certificate. Defaults to false /// </summary> [Input("skipVerify")] public string? SkipVerify { get; set; } /// <summary> /// Either OpportunisticStartTLS, MandatoryStartTLS or NoStartTLS. /// Default is OpportunisticStartTLS. /// </summary> [Input("starttlsPolicy")] public string? StarttlsPolicy { get; set; } /// <summary> /// Username for SMTP authentication /// </summary> [Input("username")] public string? Username { get; set; } public GetGrafanaGrafanaUserConfigSmtpServerArgs() { } } }
28.101449
88
0.56885
[ "ECL-2.0", "Apache-2.0" ]
pulumi/pulumi-aiven
sdk/dotnet/Inputs/GetGrafanaGrafanaUserConfigSmtpServerArgs.cs
1,939
C#
// // Copyright (c) .NET Foundation and Contributors // See LICENSE file in the project root for full license information. // using System; using System.Collections.Generic; namespace nanoFramework.Tools.Debugger.WireProtocol { public class WireProtocolRequestsStore { private readonly object _requestsLock = new object(); private readonly Dictionary<Tuple<uint, ushort>, WireProtocolRequest> _requests = new(); public void Add(WireProtocolRequest request) { lock (_requestsLock) { // it's wise to check if this key is already on the dictionary // can't use TryAdd because that's only available on the UWP API Tuple<uint, ushort> newKey = GetKey(request); if (_requests.ContainsKey(newKey)) { // remove the last one, before adding this _ = _requests.Remove(newKey); } _requests.Add(newKey, request); } } public bool Remove(Packet header) { lock (_requestsLock) { return _requests.Remove(new Tuple<uint, ushort>(header.Cmd, header.Seq)); } } public bool Remove(WireProtocolRequest request) { lock (_requestsLock) { if(_requests.Remove(GetKey(request))) { request.RequestAborted(); return true; } else { return false; } } } public int GetCount() { lock (_requestsLock) { return _requests.Count; } } public WireProtocolRequest GetByReplyHeader(Packet header) { lock (_requestsLock) { return _requests.TryGetValue(new Tuple<uint, ushort>(header.Cmd, header.SeqReply), out WireProtocolRequest requestState) ? requestState : null; } } private Tuple<uint, ushort> GetKey(WireProtocolRequest request) { return new Tuple<uint, ushort>(request.OutgoingMessage.Header.Cmd, request.OutgoingMessage.Header.Seq); } } }
28.851852
159
0.531023
[ "MIT" ]
Eclo/nf-debugger
nanoFramework.Tools.DebugLibrary.Shared/WireProtocol/WireProtocolRequestsStore.cs
2,339
C#
using System; namespace AsmResolver.DotNet.Builder { /// <summary> /// Provides a context in which a PE image construction takes place in. /// </summary> public class PEImageBuildContext { /// <summary> /// Creates a new empty build context. /// </summary> public PEImageBuildContext() { DiagnosticBag = new DiagnosticBag(); } /// <summary> /// Creates a new build context. /// </summary> /// <param name="diagnosticBag">The diagnostic bag to use.</param> public PEImageBuildContext(DiagnosticBag diagnosticBag) { DiagnosticBag = diagnosticBag ?? throw new ArgumentNullException(nameof(diagnosticBag)); } /// <summary> /// Gets the bag that collects all diagnostic information during the building process. /// </summary> public DiagnosticBag DiagnosticBag { get; } } }
28.6
100
0.567433
[ "MIT" ]
Anonym0ose/AsmResolver
src/AsmResolver.DotNet/Builder/PEImageBuildContext.cs
1,001
C#
using NetTools; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Text; using System.Web; namespace Hexasoft { public class BasicAuthentication : IHttpModule { public void Init(HttpApplication context) { context.BeginRequest += ContextBeginRequest; } private void ContextBeginRequest(object sender, EventArgs e) { if (Bypassed()) return; if (Required()) { if (!ValidateCredentials()) { var httpApplication = (HttpApplication)sender; httpApplication.Context.Response.Clear(); httpApplication.Context.Response.Status = "401 Unauthorized"; httpApplication.Context.Response.StatusCode = 401; httpApplication.Context.Response.AddHeader("WWW-Authenticate", "Basic realm=\"" + Request.Url.Host + "\""); httpApplication.CompleteRequest(); } } } private bool Bypassed() { var ip = GetIPAddress(); if (ip == null) return false; string ipRangeBypassSetting = ConfigurationManager.AppSettings["BasicAuthentication.IpRangeBypassList"]; if (string.IsNullOrEmpty(ipRangeBypassSetting)) return false; IEnumerable<IPAddressRange> ipRanges = ipRangeBypassSetting.Split('|', ';') .Select(n => IPAddressRange.TryParse(n, out var ipRange) ? ipRange : null) .Where(n => n != null); return ipRanges.Any(n => n.Contains(ip)); } protected IPAddress GetIPAddress() { System.Web.HttpContext context = System.Web.HttpContext.Current; string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (!string.IsNullOrEmpty(ipAddress)) { string[] addresses = ipAddress.Split(','); if (addresses.Length != 0 && IPAddress.TryParse(addresses[0], out var ip1)) { return ip1; } } return IPAddress.TryParse(context.Request.ServerVariables["REMOTE_ADDR"], out var ip2) ? ip2 : null; } private bool Required() { bool required = false; string requiredSetting = ConfigurationManager.AppSettings["BasicAuthentication.Required"]; if (!string.IsNullOrWhiteSpace(requiredSetting)) { requiredSetting = requiredSetting.Trim().ToLower(); required = requiredSetting == "1" || requiredSetting == "true"; } return required; } private bool ValidateCredentials() { string validUsername = ConfigurationManager.AppSettings["BasicAuthentication.Username"]; if (string.IsNullOrEmpty(validUsername)) return false; string validPassword = ConfigurationManager.AppSettings["BasicAuthentication.Password"]; if (string.IsNullOrEmpty(validPassword)) return false; string header = Request.Headers["Authorization"]; if (string.IsNullOrEmpty(header)) return false; header = header.Trim(); if (header.IndexOf("Basic ", StringComparison.InvariantCultureIgnoreCase) != 0) return false; string credentials = header.Substring(6); // Decode the Base64 encoded credentials byte[] credentialsBase64DecodedArray = Convert.FromBase64String(credentials); string decodedCredentials = Encoding.UTF8.GetString(credentialsBase64DecodedArray, 0, credentialsBase64DecodedArray.Length); // Get username and password int separatorPosition = decodedCredentials.IndexOf(':'); if (separatorPosition <= 0) return false; string username = decodedCredentials.Substring(0, separatorPosition); string password = decodedCredentials.Substring(separatorPosition + 1); if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) return false; return username.ToLower() == validUsername.ToLower() && password == validPassword; } private HttpRequest Request { get { return HttpContext.Current.Request; } } public void Dispose() { } } }
33.014085
136
0.576365
[ "MIT" ]
zurichversicherung/Hexasoft.BasicAuthentication
Hexasoft.BasicAuthentication/Hexasoft.BasicAuthentication/BasicAuthentication.cs
4,690
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 codedeploy-2014-10-06.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.CodeDeploy.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CodeDeploy.Model.Internal.MarshallTransformations { /// <summary> /// GetApplication Request Marshaller /// </summary> public class GetApplicationRequestMarshaller : IMarshaller<IRequest, GetApplicationRequest> , 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((GetApplicationRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(GetApplicationRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.CodeDeploy"); string target = "CodeDeploy_20141006.GetApplication"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2014-10-06"; request.HttpMethod = "POST"; request.ResourcePath = "/"; 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.IsSetApplicationName()) { context.Writer.WritePropertyName("applicationName"); context.Writer.Write(publicRequest.ApplicationName); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static GetApplicationRequestMarshaller _instance = new GetApplicationRequestMarshaller(); internal static GetApplicationRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetApplicationRequestMarshaller Instance { get { return _instance; } } } }
35.247619
143
0.631181
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/CodeDeploy/Generated/Model/Internal/MarshallTransformations/GetApplicationRequestMarshaller.cs
3,701
C#
using System; using System.Diagnostics; using TMPro; using UnityEngine; using UnityEngine.Events; using UnityEngine.SceneManagement; public class TimerUtil : MonoBehaviour { public UnityAction OnTimerStopped; public UnityAction<string> OnTimerUpdate; public string timerOutput; public bool HasStarted { get; private set; } [SerializeField] private float timerStart; [SerializeField] private float timerEnd; [SerializeField] private bool countsUp; [SerializeField]private TextMeshProUGUI timerText; private float _timerSeconds; private const string OutputPattern = @"mm\:ss"; private void Awake() { SceneManager.sceneLoaded += FindTimerText; FindTimerText(SceneManager.GetActiveScene(), LoadSceneMode.Additive); DontDestroyOnLoad(this); } private void FindTimerText(Scene scene, LoadSceneMode mode) { timerText = GameObject.FindWithTag("TimerText").GetComponent<TextMeshProUGUI>(); } private void Update() { if (!HasStarted) return; _timerSeconds += countsUp ? Time.deltaTime : -Time.deltaTime; var t = TimeSpan.FromSeconds(_timerSeconds); timerOutput = t.ToString(OutputPattern); timerText.text = timerOutput; if (countsUp && _timerSeconds > timerEnd || !countsUp && _timerSeconds < timerEnd) { StopTimer(); } OnTimerUpdate?.Invoke(timerOutput); } public void StartTimer() { ResetTimer(); HasStarted = true; } public void StopTimer() { HasStarted = false; OnTimerStopped?.Invoke(); } private void ResetTimer() { _timerSeconds = timerStart; } }
25.57971
88
0.647025
[ "MIT" ]
olchyk98/deadmind
Assets/Scripts/TimerUtil.cs
1,765
C#
using System; using System.Threading; using Telegram.Bot.Types.Enums; using static pmcenter.Conf; namespace pmcenter { public partial class Methods { public static async void ThrUpdateChecker() { Log("Started!", "UPDATER"); while (true) { Vars.UpdateCheckerStatus = ThreadStatus.Working; try { var Latest = Conf.CheckForUpdates(); var DisNotif = Vars.CurrentConf.DisableNotifications; // Identical with BotProcess.cs, L206. if (Conf.IsNewerVersionAvailable(Latest)) { Vars.UpdatePending = true; Vars.UpdateVersion = new Version(Latest.Latest); Vars.UpdateLevel = Latest.UpdateLevel; var UpdateString = Vars.CurrentLang.Message_UpdateAvailable .Replace("$1", Latest.Latest) .Replace("$2", Latest.Details) .Replace("$3", GetUpdateLevel(Latest.UpdateLevel)); await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID, UpdateString, ParseMode.Markdown, false, DisNotif); return; // Since this thread wouldn't be useful any longer, exit. } else { Vars.UpdatePending = false; // This part has been cut out. } } catch (Exception ex) { Log("Error during update check: " + ex.ToString(), "UPDATER", LogLevel.ERROR); } Vars.UpdateCheckerStatus = ThreadStatus.Standby; Thread.Sleep(60000); } } } }
41.057692
98
0.428571
[ "Apache-2.0" ]
ModerRAS/pmcenter
pmcenter/Methods/Threads/ThrUpdateChecker.cs
2,135
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 sesv2-2019-09-27.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SimpleEmailV2.Model { /// <summary> /// An HTTP 200 response if the request succeeds, or an error message if the request fails. /// </summary> public partial class DeleteEmailIdentityPolicyResponse : AmazonWebServiceResponse { } }
30.289474
103
0.735013
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/SimpleEmailV2/Generated/Model/DeleteEmailIdentityPolicyResponse.cs
1,151
C#
//****************************************************************************************************** // SI2.cs - Gbtc // // Copyright © 2012, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), 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.opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 01/25/2008 - J. Ritchie Carroll // Initial version of source generated. // 09/11/2008 - J. Ritchie Carroll // Converted to C#. // 08/10/2009 - Josh L. Patterson // Edited Comments. // 09/14/2009 - Stephen C. Wills // Added new header and license agreement. // 12/14/2012 - Starlynn Danyelle Gilliam // Modified Header. // //****************************************************************************************************** #region [ Contributor License Agreements ] /**************************************************************************\ Copyright © 2009 - J. Ritchie Carroll All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \**************************************************************************/ #endregion using System; using System.Text; #pragma warning disable CA1819 // Properties should not return arrays namespace Gemstone.Units { /// <summary> /// Defines constant factors based on 1024 for related binary SI units of measure used in computational measurements. /// </summary> /// <remarks> /// See <a href="http://physics.nist.gov/cuu/Units/binary.html">NIST Reference</a> for information on IEC standard names. /// </remarks> // ReSharper disable RedundantNameQualifier public static class SI2 { // Common unit factor SI names // Common unit factor SI symbols // IEC unit factor SI names // IEC unit factor SI symbols // Unit factor SI factors /// <summary> /// 1 exa, binary (E) = 1,152,921,504,606,846,976 /// </summary> /// <remarks> /// This is the common name. /// </remarks> public const long Exa = Kilo * Peta; /// <summary> /// 1 exbi (Ei) = 1,152,921,504,606,846,976 /// </summary> /// <remarks> /// This is the IEC standard name. /// </remarks> public const long Exbi = Exa; /// <summary> /// 1 peta, binary (P) = 1,125,899,906,842,624 /// </summary> /// <remarks> /// This is the common name. /// </remarks> public const long Peta = Kilo * Tera; /// <summary> /// 1 pebi (Pi) = 1,125,899,906,842,624 /// </summary> /// <remarks> /// This is the IEC standard name. /// </remarks> public const long Pebi = Peta; /// <summary> /// 1 tera, binary (T) = 1,099,511,627,776 /// </summary> /// <remarks> /// This is the common name. /// </remarks> public const long Tera = Kilo * Giga; /// <summary> /// 1 tebi (Ti) = 1,099,511,627,776 /// </summary> /// <remarks> /// This is the IEC standard name. /// </remarks> public const long Tebi = Tera; /// <summary> /// 1 giga, binary (G) = 1,073,741,824 /// </summary> /// <remarks> /// This is the common name. /// </remarks> public const long Giga = Kilo * Mega; /// <summary> /// 1 gibi (Gi) = 1,073,741,824 /// </summary> /// <remarks> /// This is the IEC standard name. /// </remarks> public const long Gibi = Giga; /// <summary> /// 1 mega, binary (M) = 1,048,576 /// </summary> /// <remarks> /// This is the common name. /// </remarks> public const long Mega = Kilo * Kilo; /// <summary> /// 1 mebi (Mi) = 1,048,576 /// </summary> /// <remarks> /// This is the IEC standard name. /// </remarks> public const long Mebi = Mega; /// <summary> /// 1 kilo, binary (K) = 1,024 /// </summary> /// <remarks> /// This is the common name. /// </remarks> public const long Kilo = 1024L; /// <summary> /// 1 kibi (Ki) = 1,024 /// </summary> /// <remarks> /// This is the IEC standard name. /// </remarks> public const long Kibi = Kilo; /// <summary> /// Gets an array of all the defined common binary unit factor SI names ordered from least (<see cref="Kilo"/>) to greatest (<see cref="Exa"/>). /// </summary> public static string[] Names { get; } = { "kilo", "mega", "giga", "tera", "peta", "exa" }; /// <summary> /// Gets an array of all the defined common binary unit factor SI prefix symbols ordered from least (<see cref="Kilo"/>) to greatest (<see cref="Exa"/>). /// </summary> public static string[] Symbols { get; } = { "K", "M", "G", "T", "P", "E" }; /// <summary> /// Gets an array of all the defined IEC binary unit factor SI names ordered from least (<see cref="Kibi"/>) to greatest (<see cref="Exbi"/>). /// </summary> public static string[] IECNames { get; } = { "kibi", "mebi", "gibi", "tebi", "pebi", "exbi" }; /// <summary> /// Gets an array of all the defined IEC binary unit factor SI prefix symbols ordered from least (<see cref="Kibi"/>) to greatest (<see cref="Exbi"/>). /// </summary> public static string[] IECSymbols { get; } = { "Ki", "Mi", "Gi", "Ti", "Pi", "Ei" }; /// <summary> /// Gets an array of all the defined binary SI unit factors ordered from least (<see cref="Kilo"/>) to greatest (<see cref="Exa"/>). /// </summary> public static long[] Factors { get; } = { Kilo, Mega, Giga, Tera, Peta, Exa }; /// <summary> /// Turns the given number of units (e.g., bytes) into a textual representation with an appropriate unit scaling /// and common named representation (e.g., KB, MB, GB, TB, etc.). /// </summary> /// <param name="totalUnits">Total units to represent textually.</param> /// <param name="unitName">Name of unit display (e.g., you could use "B" for bytes).</param> /// <param name="symbolNames">Optional SI factor symbol or name array to use during textual conversion, defaults to <see cref="Symbols"/>.</param> /// <param name="minimumFactor">Optional minimum SI factor. Defaults to <see cref="SI2.Kilo"/>.</param> /// <param name="maximumFactor">Optional maximum SI factor. Defaults to <see cref="SI2.Exa"/>.</param> /// <remarks> /// The <paramref name="symbolNames"/> array needs one string entry for each defined SI item ordered from /// least (<see cref="Kilo"/>) to greatest (<see cref="Exa"/>), see <see cref="Names"/> or <see cref="Symbols"/> /// arrays for examples. /// </remarks> /// <returns>A <see cref="string"/> representation of the number of units.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="minimumFactor"/> or <paramref name="maximumFactor"/> is not defined in <see cref="Factors"/> array.</exception> public static string ToScaledString(long totalUnits, string unitName, string[]? symbolNames = null, long minimumFactor = Kilo, long maximumFactor = Exa) => ToScaledString(totalUnits, 2, unitName, symbolNames, minimumFactor, maximumFactor); /// <summary> /// Turns the given number of units (e.g., bytes) into a textual representation with an appropriate unit scaling /// and common named representation (e.g., KB, MB, GB, TB, etc.). /// </summary> /// <param name="totalUnits">Total units to represent textually.</param> /// <param name="format">A numeric string format for scaled <paramref name="totalUnits"/>.</param> /// <param name="unitName">Name of unit display (e.g., you could use "B" for bytes).</param> /// <param name="minimumFactor">Optional minimum SI factor. Defaults to <see cref="SI2.Kilo"/>.</param> /// <param name="maximumFactor">Optional maximum SI factor. Defaults to <see cref="SI2.Exa"/>.</param> /// <remarks> /// <see cref="Symbols"/> array is used for displaying SI symbol prefix for <paramref name="unitName"/>. /// </remarks> /// <returns>A <see cref="string"/> representation of the number of units.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="minimumFactor"/> or <paramref name="maximumFactor"/> is not defined in <see cref="Factors"/> array.</exception> public static string ToScaledString(long totalUnits, string format, string unitName, long minimumFactor = Kilo, long maximumFactor = Exa) => ToScaledString(totalUnits, format, unitName, Symbols, -1, minimumFactor, maximumFactor); /// <summary> /// Turns the given number of units (e.g., bytes) into a textual representation with an appropriate unit scaling /// and common named representation (e.g., KB, MB, GB, TB, etc.). /// </summary> /// <param name="totalUnits">Total units to represent textually.</param> /// <param name="decimalPlaces">Number of decimal places to display.</param> /// <param name="unitName">Name of unit display (e.g., you could use "B" for bytes).</param> /// <param name="symbolNames">Optional SI factor symbol or name array to use during textual conversion, defaults to <see cref="Symbols"/>.</param> /// <param name="minimumFactor">Optional minimum SI factor. Defaults to <see cref="SI2.Kilo"/>.</param> /// <param name="maximumFactor">Optional maximum SI factor. Defaults to <see cref="SI2.Exa"/>.</param> /// <remarks> /// The <paramref name="symbolNames"/> array needs one string entry for each defined SI item ordered from /// least (<see cref="Kilo"/>) to greatest (<see cref="Exa"/>), see <see cref="Names"/> or <see cref="Symbols"/> /// arrays for examples. /// </remarks> /// <returns>A <see cref="string"/> representation of the number of units.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="decimalPlaces"/> cannot be negative.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="minimumFactor"/> or <paramref name="maximumFactor"/> is not defined in <see cref="Factors"/> array.</exception> public static string ToScaledString(long totalUnits, int decimalPlaces, string unitName, string[]? symbolNames = null, long minimumFactor = Kilo, long maximumFactor = Exa) { if (decimalPlaces < 0) throw new ArgumentOutOfRangeException(nameof(decimalPlaces), "decimalPlaces cannot be negative"); return ToScaledString(totalUnits, "R", unitName, symbolNames ?? Symbols, decimalPlaces, minimumFactor, maximumFactor); } /// <summary> /// Turns the given number of units (e.g., bytes) into a textual representation with an appropriate unit scaling /// given string array of factor names or symbols. /// </summary> /// <param name="totalUnits">Total units to represent textually.</param> /// <param name="format">A numeric string format for scaled <paramref name="totalUnits"/>.</param> /// <param name="unitName">Name of unit display (e.g., you could use "B" for bytes).</param> /// <param name="symbolNames">SI factor symbol or name array to use during textual conversion.</param> /// <param name="decimalPlaces">Optional number of decimal places to display.</param> /// <param name="minimumFactor">Optional minimum SI factor. Defaults to <see cref="SI2.Kilo"/>.</param> /// <param name="maximumFactor">Optional maximum SI factor. Defaults to <see cref="SI2.Exa"/>.</param> /// <remarks> /// The <paramref name="symbolNames"/> array needs one string entry for each defined SI item ordered from /// least (<see cref="Kilo"/>) to greatest (<see cref="Exa"/>), see <see cref="Names"/> or <see cref="Symbols"/> /// arrays for examples. /// </remarks> /// <returns>A <see cref="string"/> representation of the number of units.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="minimumFactor"/> or <paramref name="maximumFactor"/> is not defined in <see cref="Factors"/> array.</exception> public static string ToScaledString(long totalUnits, string format, string unitName, string[] symbolNames, int decimalPlaces = -1, long minimumFactor = Kilo, long maximumFactor = Exa) { StringBuilder image = new StringBuilder(); int minimumIndex = GetFactorIndex(minimumFactor); if (minimumIndex < 0) throw new ArgumentOutOfRangeException(nameof(minimumFactor), $"Unknown SI2 factor {minimumFactor}"); int maximumIndex = GetFactorIndex(maximumFactor); if (maximumIndex < 0) throw new ArgumentOutOfRangeException(nameof(maximumFactor), $"Unknown SI2 factor {maximumFactor}"); for (int i = maximumIndex; i >= minimumIndex; i--) { // See if total number of units ranges in the specified factor range double factor = totalUnits / (double)Factors[i]; if (factor >= 1.0D) { if (decimalPlaces > -1) factor = Math.Round(factor, decimalPlaces); image.Append(factor.ToString(format)); image.Append(' '); image.Append(symbolNames[i]); image.Append(unitName); break; } } if (image.Length == 0) { // Display total number of units image.Append(totalUnits); image.Append(' '); image.Append(unitName); } return image.ToString(); } private static int GetFactorIndex(long factor) { for (int i = 0; i < Factors.Length; i++) { if (Factors[i] == factor) return i; } return -1; } } }
47.582133
247
0.587851
[ "MIT" ]
gemstone/common
src/Gemstone/Units/SI2.cs
16,515
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/winioctl.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="SCM_PD_PASSTHROUGH_INVDIMM_OUTPUT" /> struct.</summary> public static unsafe partial class SCM_PD_PASSTHROUGH_INVDIMM_OUTPUTTests { /// <summary>Validates that the <see cref="SCM_PD_PASSTHROUGH_INVDIMM_OUTPUT" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<SCM_PD_PASSTHROUGH_INVDIMM_OUTPUT>(), Is.EqualTo(sizeof(SCM_PD_PASSTHROUGH_INVDIMM_OUTPUT))); } /// <summary>Validates that the <see cref="SCM_PD_PASSTHROUGH_INVDIMM_OUTPUT" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(SCM_PD_PASSTHROUGH_INVDIMM_OUTPUT).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="SCM_PD_PASSTHROUGH_INVDIMM_OUTPUT" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(SCM_PD_PASSTHROUGH_INVDIMM_OUTPUT), Is.EqualTo(12)); } }
41.714286
145
0.74726
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
tests/Interop/Windows/Windows/um/winioctl/SCM_PD_PASSTHROUGH_INVDIMM_OUTPUTTests.cs
1,462
C#
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // ReSharper disable CheckNamespace // ReSharper disable CommentTypo // ReSharper disable IdentifierTypo // ReSharper disable LocalizableElement // ReSharper disable MemberCanBePrivate.Global // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable UnusedType.Global /* BusyControllerTest.cs -- * Ars Magna project, http://arsmagna.ru */ #region Using directives using System.Drawing; using System.Threading; using System.Windows.Forms; using AM.Threading; using AM.Windows.Forms; #endregion #nullable enable namespace FormsTests { public sealed class BusyControllerTest : IFormsTest { #region IFormsTest members public void RunTest ( IWin32Window? ownerWindow ) { using var form = new Form { Size = new Size(800, 600) }; var firstButton = new Button { Text = "Push me 1", Location = new Point(10, 100) }; form.Controls.Add(firstButton); var secondButton = new Button { Text = "Push me 2", Location = new Point(200, 100) }; form.Controls.Add(secondButton); var state = new BusyState(); var stripe = new BusyStripe { Dock = DockStyle.Top, ForeColor = Color.LimeGreen, Height = 20, Text = "I am very busy" }; stripe.SubscribeTo(state); form.Controls.Add(stripe); var controller = new BusyController { State = state }; controller.Controls.Add(firstButton); controller.Controls.Add(secondButton); controller.ExceptionOccur += (_, args) => { ExceptionBox.Show(ownerWindow, args.Exception); }; void SleepAction() { Thread.Sleep(3000); } firstButton.Click += (_, _) => { controller.Run(SleepAction); }; secondButton.Click += (_, _) => { controller.RunAsync(SleepAction); }; form.ShowDialog(ownerWindow); } #endregion } }
24.605769
84
0.527159
[ "MIT" ]
amironov73/ManagedIrbis5
Source/Tests/FormsTests/Source/Tests/BusyControllerTest.cs
2,561
C#
namespace Mikabrytu.LD46.Events { public class PlayerChangeBPMEvent : BaseEvent { public bool isIncreasing; public PlayerChangeBPMEvent(bool isIncreasing) { this.isIncreasing = isIncreasing; } } }
21.166667
54
0.629921
[ "MIT" ]
mikabrytu/ldj46-ghost-game
Ludum Dare 46/Assets/Scripts/Event/PlayerChangeBPMEvent.cs
256
C#
namespace RecepiesProject.Web.Tests { using System; using System.Linq; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using Xunit; public class SeleniumTests : IClassFixture<SeleniumServerFactory<Startup>>, IDisposable { private readonly SeleniumServerFactory<Startup> server; private readonly IWebDriver browser; public SeleniumTests(SeleniumServerFactory<Startup> server) { this.server = server; server.CreateClient(); var opts = new ChromeOptions(); opts.AddArguments("--headless"); opts.AcceptInsecureCertificates = true; this.browser = new ChromeDriver(opts); } [Fact(Skip = "Example test. Disabled for CI.")] public void FooterOfThePageContainsPrivacyLink() { this.browser.Navigate().GoToUrl(this.server.RootUri); Assert.EndsWith( "/Home/Privacy", this.browser.FindElements(By.CssSelector("footer a")).First().GetAttribute("href")); } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { this.server?.Dispose(); this.browser?.Dispose(); } } } }
27.901961
100
0.572734
[ "Apache-2.0" ]
AKermanov/recipes-project
src/Tests/RecepiesProject.Web.Tests/SeleniumTests.cs
1,425
C#
/* Copyright 2010-2013 10gen Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using MongoDB.Bson.IO; using NUnit.Framework; namespace MongoDB.BsonUnitTests.IO { [TestFixture] public class MultiChunkBufferTests { [Test] public void TestGetSingleChunkSlice() { var chunkSize = BsonChunkPool.Default.ChunkSize; var capacity = chunkSize * 3; using (var buffer = ByteBufferFactory.Create(BsonChunkPool.Default, capacity)) { buffer.Length = capacity; buffer.MakeReadOnly(); var slice = buffer.GetSlice(chunkSize, 1); Assert.IsInstanceOf<SingleChunkBuffer>(slice); } } [Test] public void TestGetMultipleChunkSlice() { var chunkSize = BsonChunkPool.Default.ChunkSize; var capacity = chunkSize * 3; using (var buffer = ByteBufferFactory.Create(BsonChunkPool.Default, capacity)) { buffer.Length = capacity; buffer.MakeReadOnly(); var slice = buffer.GetSlice(chunkSize, chunkSize + 1); Assert.IsInstanceOf<MultiChunkBuffer>(slice); } } } }
33.245283
90
0.629966
[ "Apache-2.0" ]
ExM/mongo-csharp-driver
MongoDB.BsonUnitTests/IO/MultiChunkBufferTests.cs
1,764
C#
using log4net; using log4net.Config; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Nssol.Platypus.Infrastructure; using System; using System.IO; using System.Reflection; using System.Text; using System.Text.RegularExpressions; namespace Nssol.Platypus { /// <summary> /// エントリポイントをもつクラス /// </summary> public class Program { /// <summary> /// プログラムのエントリポイント /// </summary> /// <param name="args">実行時引数</param> public static void Main(string[] args) { // https://github.com/aspnet/EntityFrameworkCore/issues/9033 // var host = BuildWebHost(args); var host = BuildWebHost2(args); ConfigureLog4Net(@"./log4net.config"); host.Run(); } private static IWebHost BuildWebHost2(string[] args) { return WebHost.CreateDefaultBuilder(args) .CaptureStartupErrors(true) // ログ設定 .ConfigureLogging((hostingContext, logging) => { logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); logging.AddDebug(); logging.AddProvider(new Log4NetProvider()); }) .UseStartup<Startup>() .UseUrls("http://*:5000") .Build(); } /// <summary> /// log4net の設定ファイルを読み込み、環境変数を置換する /// ※本来log4netの機能だけでできるはず。.netcore の問題か動かないので自作した。 /// </summary> /// <param name="filename">ファイル名</param> /// <returns>読み込み結果</returns> private static Stream ConvertLogConfigEnvVariables(string filename) { using (Stream fs = new FileStream(filename, FileMode.Open)) using (StreamReader reader = new StreamReader(fs, Encoding.UTF8)) { string content = reader.ReadToEnd(); Regex r = new Regex(@"\$\{\s*(.*)\s*\}"); StringBuilder buf = new StringBuilder(); int lastIndex = 0; MatchCollection mc = r.Matches(content); foreach (Match m in mc) { buf.Append(content.Substring(lastIndex, m.Index - lastIndex)); string envName = m.Groups[1].Value; string envValue = Environment.GetEnvironmentVariable(envName); if (!string.IsNullOrEmpty(envValue)) { buf.Append(envValue); } lastIndex = m.Index + m.Length; } buf.Append(content.Substring(lastIndex)); return new MemoryStream(Encoding.UTF8.GetBytes(buf.ToString())); } } /// <summary> /// Log4Netを構成します。 /// </summary> /// <param name="log4netFileName">log4netconfigファイルパス</param> private static void ConfigureLog4Net(string log4netFileName) { var assembly = typeof(LogManager).GetTypeInfo().Assembly; var repository = LogManager.GetRepository(assembly); XmlConfigurator.Configure(repository, ConvertLogConfigEnvVariables(log4netFileName)); } } }
34.424242
97
0.552523
[ "Apache-2.0" ]
yonetatuu/kamonohashi
web-api/platypus/platypus/Program.cs
3,636
C#
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated> using System; using System.Collections.Generic; namespace EFCore_12_Samurai_01.Models { public partial class Company { public Company() { Users = new HashSet<User>(); } public int CompanyId { get; set; } public string CompanyName { get; set; } public virtual ICollection<User> Users { get; set; } } }
24.842105
96
0.627119
[ "MIT" ]
philanderson888/c-sharp
EFCore_12_Samurai_01/Models/Company.cs
474
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics.ContractsLight; using System.Linq; using System.Text; using BuildXL.Cache.ContentStore.Hashing; using BuildXL.Cache.ContentStore.Tracing.Internal; using BuildXL.Cache.ContentStore.Utils; using BuildXL.Cache.MemoizationStore.Interfaces.Sessions; using BuildXL.Utilities; using BuildXL.Utilities.Collections; namespace BuildXL.Cache.ContentStore.Distributed.NuCache.EventStreaming { /// <summary> /// Type of an event happened in the system. /// </summary> public enum EventKind { /// <nodoc /> AddLocation, /// <nodoc /> RemoveLocation, /// <nodoc /> Touch, /// <nodoc /> Blob, /// <nodoc /> AddLocationWithoutTouching, /// <nodoc /> UpdateMetadataEntry, } /// <summary> /// Base class that describe the event. /// </summary> public abstract class ContentLocationEventData : IEquatable<ContentLocationEventData> { // Need some wiggle room for auxiliary instance data needed for assessing serialized instance size. private const int SerializedSizeBase = 128; /// <summary> /// Indicates whether an Add/Remove event is related to reconciliation. /// NOTE: This is not (de)serialized, but is determined when specifically handling a reconciliation event. /// </summary> public bool Reconciling { get; internal set; } /// <nodoc /> public EventKind Kind { get; } /// <nodoc /> protected internal virtual EventKind SerializationKind => Kind; /// <summary> /// A current machine id. /// </summary> public MachineId Sender { get; } /// <summary> /// A list of affected content hashes. /// </summary> /// <remarks> /// The list is not null or empty. /// </remarks> public IReadOnlyList<ShortHash> ContentHashes { get; } /// <nodoc /> protected ContentLocationEventData(EventKind kind, MachineId sender, IReadOnlyList<ShortHash> contentHashes) { Contract.Requires(contentHashes != null); Kind = kind; Sender = sender; ContentHashes = contentHashes; } /// <nodoc /> public static ContentLocationEventData Deserialize(BuildXLReader reader, DateTime eventTimeUtc) { Contract.Requires(reader != null); var kind = (EventKind)reader.ReadByte(); var sender = MachineId.Deserialize(reader); var hashes = reader.ReadReadOnlyList(r => r.ReadShortHash()); switch (kind) { case EventKind.AddLocation: case EventKind.AddLocationWithoutTouching: return new AddContentLocationEventData(sender, hashes, reader.ReadReadOnlyList(r => r.ReadInt64Compact()), touch: kind == EventKind.AddLocation); case EventKind.RemoveLocation: return new RemoveContentLocationEventData(sender, hashes); case EventKind.Touch: return new TouchContentLocationEventData(sender, hashes, eventTimeUtc); case EventKind.Blob: return new BlobContentLocationEventData(sender, reader.ReadString()); case EventKind.UpdateMetadataEntry: return new UpdateMetadataEntryEventData(sender, reader); default: throw new ArgumentOutOfRangeException($"Unknown event kind '{kind}'."); } } /// <nodoc /> public virtual void Serialize(BuildXLWriter writer) { writer.Write((byte)SerializationKind); Sender.Serialize(writer); writer.WriteReadOnlyList(ContentHashes, (w, hash) => w.Write(hash)); switch (this) { case AddContentLocationEventData addContentLocationEventData: writer.WriteReadOnlyList(addContentLocationEventData.ContentSizes, (w, size) => w.WriteCompact(size)); break; case RemoveContentLocationEventData removeContentLocationEventData: case TouchContentLocationEventData touchContentLocationEventData: // Do nothing. No extra data. Touch timestamp is taken from event enqueue time break; case BlobContentLocationEventData reconcileContentLocationEventData: writer.Write(reconcileContentLocationEventData.BlobId); break; } } /// <summary> /// Returns an estimated size of the instance /// </summary> public long EstimateSerializedInstanceSize() { switch (this) { case AddContentLocationEventData addContentLocationEventData: return SerializedSizeBase + ContentHashes.Count * ShortHash.SerializedLength + addContentLocationEventData.ContentSizes.Count * sizeof(long); default: return SerializedSizeBase + ContentHashes.Count * ShortHash.SerializedLength; } } /// <summary> /// Splits the current instance into a smaller instances /// </summary> public IReadOnlyList<ContentLocationEventData> Split(OperationContext context, long maxEstimatedSize) { // First, need to compute the number of hashes that will fit into maxEstimatedSize. var maxHashCount = maxContentHashesCount(maxEstimatedSize); // Then we need to split the instance into a sequence of instances. var hashes = ContentHashes.Split(maxHashCount).ToList(); var result = new List<ContentLocationEventData>(hashes.Count); Contract.Assert(hashes.Sum(c => c.Count) == ContentHashes.Count); switch (this) { case AddContentLocationEventData addContentLocationEventData: var contentSizes = addContentLocationEventData.ContentSizes.Split(maxHashCount).ToList(); Contract.Assert(hashes.Count == contentSizes.Count); result.AddRange(hashes.Select((t, index) => new AddContentLocationEventData(Sender, t, contentSizes[index], addContentLocationEventData.Touch))); break; case RemoveContentLocationEventData _: result.AddRange(hashes.Select(t => new RemoveContentLocationEventData(Sender, t))); break; case TouchContentLocationEventData touchContentLocationEventData: result.AddRange(hashes.Select(t => new TouchContentLocationEventData(Sender, t, touchContentLocationEventData.AccessTime))); break; } foreach (var r in result) { var estimatedSize = r.EstimateSerializedInstanceSize(); if (estimatedSize > maxEstimatedSize) { context.TracingContext.Debug($"An estimated size is '{estimatedSize}' is greater then the max size '{maxEstimatedSize}' for event '{r.Kind}'.", component: nameof(ContentLocationEventData)); } } return result; int maxContentHashesCount(long estimatedSize) { switch (this) { case AddContentLocationEventData _: return (int)(estimatedSize - SerializedSizeBase) / (ShortHash.SerializedLength + sizeof(long)); default: return (int)(estimatedSize - SerializedSizeBase) / (ShortHash.SerializedLength); } } } /// <inheritdoc /> public override bool Equals(object obj) { return EqualityComparer<ContentLocationEventData>.Default.Equals(this, obj as ContentLocationEventData); } /// <inheritdoc /> public override int GetHashCode() { return (Kind.GetHashCode(), Sender.GetHashCode(), ContentHashes.SequenceHashCode()).GetHashCode(); } /// <nodoc /> public virtual bool Equals(ContentLocationEventData other) { return Kind == other.Kind && Sender == other.Sender && ContentHashes.SequenceEqual(other.ContentHashes); } } /// <nodoc /> public sealed class AddContentLocationEventData : ContentLocationEventData { /// <summary> /// A list of content sizes associated with <see cref="ContentLocationEventData.ContentHashes"/>. /// </summary> public IReadOnlyList<long> ContentSizes { get; } /// <summary> /// Whether or not to extend the lifetime of the content. /// </summary> public bool Touch { get; } /// <inheritdoc /> protected internal override EventKind SerializationKind => Touch ? EventKind.AddLocation : EventKind.AddLocationWithoutTouching; /// <nodoc /> public AddContentLocationEventData(MachineId sender, IReadOnlyList<ShortHashWithSize> addedContent, bool touch = true) : this(sender, addedContent.SelectList(c => c.Hash), addedContent.SelectList(c => c.Size), touch) { } /// <nodoc /> public AddContentLocationEventData(MachineId sender, IReadOnlyList<ShortHash> contentHashes, IReadOnlyList<long> contentSizes, bool touch = true) : base(EventKind.AddLocation, sender, contentHashes) { Contract.Requires(contentSizes != null); Contract.Requires(contentSizes.Count == contentHashes.Count); ContentSizes = contentSizes; Touch = touch; } /// <inheritdoc /> public override string ToString() { var sb = new StringBuilder(); for (int i = 0; i < ContentHashes.Count; i++) { sb.Append($"Hash={ContentHashes[i]}, Size={ContentSizes[i]}"); } return $"Event: {Kind}, Sender: {Sender}, Touch: {Touch}, {sb}"; } /// <inheritdoc /> public override bool Equals(ContentLocationEventData other) { var rhs = (AddContentLocationEventData)other; return base.Equals(other) && (Touch == rhs.Touch) && ContentSizes.SequenceEqual(rhs.ContentSizes); } /// <inheritdoc /> public override int GetHashCode() { return (base.GetHashCode(), ContentSizes.GetHashCode(), Touch).GetHashCode(); } } /// <nodoc /> public sealed class RemoveContentLocationEventData : ContentLocationEventData { /// <nodoc /> public RemoveContentLocationEventData(MachineId sender, IReadOnlyList<ShortHash> contentHashes) : base(EventKind.RemoveLocation, sender, contentHashes) { } /// <inheritdoc /> public override string ToString() { return $"Event: {Kind}, Sender: {Sender}, {string.Join(", ", ContentHashes)}"; } } /// <nodoc /> public sealed class BlobContentLocationEventData : ContentLocationEventData { /// <summary> /// The blob identifier of the reconciliation blob /// </summary> public string BlobId { get; } /// <nodoc /> public BlobContentLocationEventData(MachineId sender, string blobId) : base(EventKind.Blob, sender, CollectionUtilities.EmptyArray<ShortHash>()) { BlobId = blobId; } } /// <nodoc /> public sealed class UpdateMetadataEntryEventData : ContentLocationEventData { /// <summary> /// The strong fingerprint key of the content hash list entry /// </summary> public StrongFingerprint StrongFingerprint { get; } /// <summary> /// The metadata entry /// </summary> public MetadataEntry Entry { get; } /// <nodoc /> public UpdateMetadataEntryEventData(MachineId sender, StrongFingerprint strongFingerprint, MetadataEntry entry) : base(EventKind.UpdateMetadataEntry, sender, CollectionUtilities.EmptyArray<ShortHash>()) { StrongFingerprint = strongFingerprint; Entry = entry; } /// <nodoc /> public UpdateMetadataEntryEventData(MachineId sender, BuildXLReader reader) : base(EventKind.UpdateMetadataEntry, sender, CollectionUtilities.EmptyArray<ShortHash>()) { StrongFingerprint = StrongFingerprint.Deserialize(reader); Entry = MetadataEntry.Deserialize(reader); } /// <inheritdoc /> public override void Serialize(BuildXLWriter writer) { base.Serialize(writer); StrongFingerprint.Serialize(writer); Entry.Serialize(writer); } } /// <nodoc /> public sealed class TouchContentLocationEventData : ContentLocationEventData { /// <nodoc /> public TouchContentLocationEventData(MachineId sender, IReadOnlyList<ShortHash> contentHashes, DateTime accessTime) : base(EventKind.Touch, sender, contentHashes) { AccessTime = accessTime; } /// <summary> /// Date and time when the content was accessed for the last time. /// </summary> public DateTime AccessTime { get; } /// <inheritdoc /> public override string ToString() { return $"{base.ToString()}, AccessTime: {AccessTime}"; } /// <inheritdoc /> public override bool Equals(ContentLocationEventData other) { var otherTouch = (TouchContentLocationEventData)other; return base.Equals(other) && AccessTime == otherTouch.AccessTime; } /// <inheritdoc /> public override int GetHashCode() { return (base.GetHashCode(), AccessTime.GetHashCode()).GetHashCode(); } } }
38.224543
210
0.585314
[ "MIT" ]
Microsoft/BuildXL
Public/Src/Cache/ContentStore/Distributed/NuCache/EventStreaming/ContentLocationEventData.cs
14,640
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.md file in the project root for more information. using System.Collections.Immutable; using System.ComponentModel.Composition; using Microsoft.VisualStudio.ProjectSystem.Properties; using Microsoft.VisualStudio.ProjectSystem.Tree.Dependencies.CrossTarget; using Microsoft.VisualStudio.ProjectSystem.Tree.Dependencies.Models; using Microsoft.VisualStudio.ProjectSystem.Tree.Dependencies.Snapshot; using Microsoft.VisualStudio.ProjectSystem.Tree.Dependencies.Subscriptions.RuleHandlers; using Microsoft.VisualStudio.ProjectSystem.VS.Tree.Dependencies; using EventData = System.Tuple< Microsoft.VisualStudio.ProjectSystem.IProjectSubscriptionUpdate, Microsoft.VisualStudio.ProjectSystem.IProjectSharedFoldersSnapshot, Microsoft.VisualStudio.ProjectSystem.Properties.IProjectCatalogSnapshot, Microsoft.VisualStudio.ProjectSystem.IProjectCapabilitiesSnapshot>; namespace Microsoft.VisualStudio.ProjectSystem.Tree.Dependencies.Subscriptions { [Export(typeof(IDependencyCrossTargetSubscriber))] [AppliesTo(ProjectCapability.DependenciesTree)] internal sealed class DependencySharedProjectsSubscriber : DependencyRulesSubscriberBase<EventData> { private readonly DependenciesSnapshotProvider _dependenciesSnapshotProvider; [ImportingConstructor] public DependencySharedProjectsSubscriber( IProjectThreadingService threadingService, IUnconfiguredProjectTasksService tasksService, DependenciesSnapshotProvider dependenciesSnapshotProvider) : base(threadingService, tasksService) { _dependenciesSnapshotProvider = dependenciesSnapshotProvider; } protected override void SubscribeToConfiguredProject( ConfiguredProject configuredProject, IProjectSubscriptionService subscriptionService) { Subscribe( configuredProject, subscriptionService.ProjectRuleSource, ruleNames: new[] { ConfigurationGeneral.SchemaName }, "Dependencies Shared Projects Input: {1}", blocks => ProjectDataSources.SyncLinkTo( blocks.Intermediate.SyncLinkOptions(), subscriptionService.SharedFoldersSource.SourceBlock.SyncLinkOptions(), subscriptionService.ProjectCatalogSource.SourceBlock.SyncLinkOptions(), configuredProject.Capabilities.SourceBlock.SyncLinkOptions(), blocks.Action, linkOptions: DataflowOption.PropagateCompletion)); } protected override IProjectCapabilitiesSnapshot GetCapabilitiesSnapshot(EventData e) => e.Item4; protected override ProjectConfiguration GetProjectConfiguration(EventData e) => e.Item1.ProjectConfiguration; protected override void Handle( string projectFullPath, AggregateCrossTargetProjectContext currentAggregateContext, TargetFramework targetFrameworkToUpdate, EventData e) { IProjectSharedFoldersSnapshot sharedProjectsUpdate = e.Item2; IProjectCatalogSnapshot catalogs = e.Item3; var changesBuilder = new DependenciesChangesBuilder(); ProcessSharedProjectsUpdates(sharedProjectsUpdate, targetFrameworkToUpdate, changesBuilder); IDependenciesChanges? changes = changesBuilder.TryBuildChanges(); if (changes != null) { RaiseDependenciesChanged(targetFrameworkToUpdate, changes, currentAggregateContext, catalogs); } } private void ProcessSharedProjectsUpdates( IProjectSharedFoldersSnapshot sharedFolders, TargetFramework targetFramework, DependenciesChangesBuilder changesBuilder) { Requires.NotNull(sharedFolders, nameof(sharedFolders)); Requires.NotNull(targetFramework, nameof(targetFramework)); Requires.NotNull(changesBuilder, nameof(changesBuilder)); DependenciesSnapshot snapshot = _dependenciesSnapshotProvider.CurrentSnapshot; if (!snapshot.DependenciesByTargetFramework.TryGetValue(targetFramework, out TargetedDependenciesSnapshot? targetedSnapshot)) { return; } IEnumerable<string> sharedFolderProjectPaths = sharedFolders.Value.Select(sf => sf.ProjectPath); var currentSharedImportNodePaths = targetedSnapshot.Dependencies .Where(pair => pair.Flags.Contains(DependencyTreeFlags.SharedProjectDependency)) .Select(pair => pair.FilePath!) .ToList(); var diff = new SetDiff<string>(currentSharedImportNodePaths, sharedFolderProjectPaths); // process added nodes foreach (string addedSharedImportPath in diff.Added) { IDependencyModel added = new SharedProjectDependencyModel( addedSharedImportPath, addedSharedImportPath, isResolved: true, isImplicit: false, properties: ImmutableStringDictionary<string>.EmptyOrdinal); changesBuilder.Added(added); } // process removed nodes foreach (string removedSharedImportPath in diff.Removed) { bool exists = currentSharedImportNodePaths.Any(nodePath => PathHelper.IsSamePath(nodePath, removedSharedImportPath)); if (exists) { changesBuilder.Removed( ProjectRuleHandler.ProviderTypeString, dependencyId: removedSharedImportPath); } } } } }
47.897638
201
0.673681
[ "MIT" ]
brunom/project-system
src/Microsoft.VisualStudio.ProjectSystem.Managed/ProjectSystem/Tree/Dependencies/Subscriptions/DependencySharedProjectsSubscriber.cs
5,959
C#
// <auto-generated/> // Contents of: hl7.fhir.r2.core version: 1.0.2 using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Hl7.Fhir.Introspection; using Hl7.Fhir.Serialization; using Hl7.Fhir.Specification; using Hl7.Fhir.Utility; using Hl7.Fhir.Validation; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ namespace Hl7.Fhir.Model { /// <summary> /// Contract /// </summary> [Serializable] [DataContract] [FhirType("Contract", IsResource=true)] public partial class Contract : Hl7.Fhir.Model.DomainResource { /// <summary> /// FHIR Type Name /// </summary> public override string TypeName { get { return "Contract"; } } /// <summary> /// Contract Actor /// </summary> [Serializable] [DataContract] [FhirType("Contract#Actor", IsNestedType=true)] public partial class ActorComponent : Hl7.Fhir.Model.BackboneElement { /// <summary> /// FHIR Type Name /// </summary> public override string TypeName { get { return "Contract#Actor"; } } /// <summary> /// Contract Actor Type /// </summary> [FhirElement("entity", Order=40)] [CLSCompliant(false)] [References("Contract","Device","Group","Location","Organization","Patient","Practitioner","RelatedPerson","Substance")] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.ResourceReference Entity { get { return _Entity; } set { _Entity = value; OnPropertyChanged("Entity"); } } private Hl7.Fhir.Model.ResourceReference _Entity; /// <summary> /// Contract Actor Role /// </summary> [FhirElement("role", Order=50)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.CodeableConcept> Role { get { if(_Role==null) _Role = new List<Hl7.Fhir.Model.CodeableConcept>(); return _Role; } set { _Role = value; OnPropertyChanged("Role"); } } private List<Hl7.Fhir.Model.CodeableConcept> _Role; public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as ActorComponent; if (dest == null) { throw new ArgumentException("Can only copy to an object of the same type", "other"); } base.CopyTo(dest); if(Entity != null) dest.Entity = (Hl7.Fhir.Model.ResourceReference)Entity.DeepCopy(); if(Role != null) dest.Role = new List<Hl7.Fhir.Model.CodeableConcept>(Role.DeepCopy()); return dest; } public override IDeepCopyable DeepCopy() { return CopyTo(new ActorComponent()); } public override bool Matches(IDeepComparable other) { var otherT = other as ActorComponent; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(Entity, otherT.Entity)) return false; if( !DeepComparable.Matches(Role, otherT.Role)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as ActorComponent; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(Entity, otherT.Entity)) return false; if( !DeepComparable.IsExactly(Role, otherT.Role)) return false; return true; } [IgnoreDataMember] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (Entity != null) yield return Entity; foreach (var elem in Role) { if (elem != null) yield return elem; } } } [IgnoreDataMember] public override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (Entity != null) yield return new ElementValue("entity", Entity); foreach (var elem in Role) { if (elem != null) yield return new ElementValue("role", elem); } } } } /// <summary> /// Contract Valued Item /// </summary> [Serializable] [DataContract] [FhirType("Contract#ValuedItem", IsNestedType=true)] public partial class ValuedItemComponent : Hl7.Fhir.Model.BackboneElement { /// <summary> /// FHIR Type Name /// </summary> public override string TypeName { get { return "Contract#ValuedItem"; } } /// <summary> /// Contract Valued Item Type /// </summary> [FhirElement("entity", Order=40, Choice=ChoiceType.DatatypeChoice)] [CLSCompliant(false)] [AllowedTypes(typeof(Hl7.Fhir.Model.CodeableConcept),typeof(Hl7.Fhir.Model.ResourceReference))] [DataMember] public Hl7.Fhir.Model.DataType Entity { get { return _Entity; } set { _Entity = value; OnPropertyChanged("Entity"); } } private Hl7.Fhir.Model.DataType _Entity; /// <summary> /// Contract Valued Item Identifier /// </summary> [FhirElement("identifier", Order=50)] [DataMember] public Hl7.Fhir.Model.Identifier Identifier { get { return _Identifier; } set { _Identifier = value; OnPropertyChanged("Identifier"); } } private Hl7.Fhir.Model.Identifier _Identifier; /// <summary> /// Contract Valued Item Effective Tiem /// </summary> [FhirElement("effectiveTime", Order=60)] [DataMember] public Hl7.Fhir.Model.FhirDateTime EffectiveTimeElement { get { return _EffectiveTimeElement; } set { _EffectiveTimeElement = value; OnPropertyChanged("EffectiveTimeElement"); } } private Hl7.Fhir.Model.FhirDateTime _EffectiveTimeElement; /// <summary> /// Contract Valued Item Effective Tiem /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [IgnoreDataMember] public string EffectiveTime { get { return EffectiveTimeElement != null ? EffectiveTimeElement.Value : null; } set { if (value == null) EffectiveTimeElement = null; else EffectiveTimeElement = new Hl7.Fhir.Model.FhirDateTime(value); OnPropertyChanged("EffectiveTime"); } } /// <summary> /// Count of Contract Valued Items /// </summary> [FhirElement("quantity", Order=70)] [DataMember] public Hl7.Fhir.Model.Quantity Quantity { get { return _Quantity; } set { _Quantity = value; OnPropertyChanged("Quantity"); } } private Hl7.Fhir.Model.Quantity _Quantity; /// <summary> /// Contract Valued Item fee, charge, or cost /// </summary> [FhirElement("unitPrice", Order=80)] [DataMember] public Hl7.Fhir.Model.Quantity UnitPrice { get { return _UnitPrice; } set { _UnitPrice = value; OnPropertyChanged("UnitPrice"); } } private Hl7.Fhir.Model.Quantity _UnitPrice; /// <summary> /// Contract Valued Item Price Scaling Factor /// </summary> [FhirElement("factor", Order=90)] [DataMember] public Hl7.Fhir.Model.FhirDecimal FactorElement { get { return _FactorElement; } set { _FactorElement = value; OnPropertyChanged("FactorElement"); } } private Hl7.Fhir.Model.FhirDecimal _FactorElement; /// <summary> /// Contract Valued Item Price Scaling Factor /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [IgnoreDataMember] public decimal? Factor { get { return FactorElement != null ? FactorElement.Value : null; } set { if (value == null) FactorElement = null; else FactorElement = new Hl7.Fhir.Model.FhirDecimal(value); OnPropertyChanged("Factor"); } } /// <summary> /// Contract Valued Item Difficulty Scaling Factor /// </summary> [FhirElement("points", Order=100)] [DataMember] public Hl7.Fhir.Model.FhirDecimal PointsElement { get { return _PointsElement; } set { _PointsElement = value; OnPropertyChanged("PointsElement"); } } private Hl7.Fhir.Model.FhirDecimal _PointsElement; /// <summary> /// Contract Valued Item Difficulty Scaling Factor /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [IgnoreDataMember] public decimal? Points { get { return PointsElement != null ? PointsElement.Value : null; } set { if (value == null) PointsElement = null; else PointsElement = new Hl7.Fhir.Model.FhirDecimal(value); OnPropertyChanged("Points"); } } /// <summary> /// Total Contract Valued Item Value /// </summary> [FhirElement("net", Order=110)] [DataMember] public Hl7.Fhir.Model.Quantity Net { get { return _Net; } set { _Net = value; OnPropertyChanged("Net"); } } private Hl7.Fhir.Model.Quantity _Net; public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as ValuedItemComponent; if (dest == null) { throw new ArgumentException("Can only copy to an object of the same type", "other"); } base.CopyTo(dest); if(Entity != null) dest.Entity = (Hl7.Fhir.Model.DataType)Entity.DeepCopy(); if(Identifier != null) dest.Identifier = (Hl7.Fhir.Model.Identifier)Identifier.DeepCopy(); if(EffectiveTimeElement != null) dest.EffectiveTimeElement = (Hl7.Fhir.Model.FhirDateTime)EffectiveTimeElement.DeepCopy(); if(Quantity != null) dest.Quantity = (Hl7.Fhir.Model.Quantity)Quantity.DeepCopy(); if(UnitPrice != null) dest.UnitPrice = (Hl7.Fhir.Model.Quantity)UnitPrice.DeepCopy(); if(FactorElement != null) dest.FactorElement = (Hl7.Fhir.Model.FhirDecimal)FactorElement.DeepCopy(); if(PointsElement != null) dest.PointsElement = (Hl7.Fhir.Model.FhirDecimal)PointsElement.DeepCopy(); if(Net != null) dest.Net = (Hl7.Fhir.Model.Quantity)Net.DeepCopy(); return dest; } public override IDeepCopyable DeepCopy() { return CopyTo(new ValuedItemComponent()); } public override bool Matches(IDeepComparable other) { var otherT = other as ValuedItemComponent; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(Entity, otherT.Entity)) return false; if( !DeepComparable.Matches(Identifier, otherT.Identifier)) return false; if( !DeepComparable.Matches(EffectiveTimeElement, otherT.EffectiveTimeElement)) return false; if( !DeepComparable.Matches(Quantity, otherT.Quantity)) return false; if( !DeepComparable.Matches(UnitPrice, otherT.UnitPrice)) return false; if( !DeepComparable.Matches(FactorElement, otherT.FactorElement)) return false; if( !DeepComparable.Matches(PointsElement, otherT.PointsElement)) return false; if( !DeepComparable.Matches(Net, otherT.Net)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as ValuedItemComponent; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(Entity, otherT.Entity)) return false; if( !DeepComparable.IsExactly(Identifier, otherT.Identifier)) return false; if( !DeepComparable.IsExactly(EffectiveTimeElement, otherT.EffectiveTimeElement)) return false; if( !DeepComparable.IsExactly(Quantity, otherT.Quantity)) return false; if( !DeepComparable.IsExactly(UnitPrice, otherT.UnitPrice)) return false; if( !DeepComparable.IsExactly(FactorElement, otherT.FactorElement)) return false; if( !DeepComparable.IsExactly(PointsElement, otherT.PointsElement)) return false; if( !DeepComparable.IsExactly(Net, otherT.Net)) return false; return true; } [IgnoreDataMember] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (Entity != null) yield return Entity; if (Identifier != null) yield return Identifier; if (EffectiveTimeElement != null) yield return EffectiveTimeElement; if (Quantity != null) yield return Quantity; if (UnitPrice != null) yield return UnitPrice; if (FactorElement != null) yield return FactorElement; if (PointsElement != null) yield return PointsElement; if (Net != null) yield return Net; } } [IgnoreDataMember] public override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (Entity != null) yield return new ElementValue("entity", Entity); if (Identifier != null) yield return new ElementValue("identifier", Identifier); if (EffectiveTimeElement != null) yield return new ElementValue("effectiveTime", EffectiveTimeElement); if (Quantity != null) yield return new ElementValue("quantity", Quantity); if (UnitPrice != null) yield return new ElementValue("unitPrice", UnitPrice); if (FactorElement != null) yield return new ElementValue("factor", FactorElement); if (PointsElement != null) yield return new ElementValue("points", PointsElement); if (Net != null) yield return new ElementValue("net", Net); } } } /// <summary> /// Contract Signer /// </summary> [Serializable] [DataContract] [FhirType("Contract#Signatory", IsNestedType=true)] public partial class SignatoryComponent : Hl7.Fhir.Model.BackboneElement { /// <summary> /// FHIR Type Name /// </summary> public override string TypeName { get { return "Contract#Signatory"; } } /// <summary> /// Contract Signer Type /// </summary> [FhirElement("type", Order=40)] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.Coding Type { get { return _Type; } set { _Type = value; OnPropertyChanged("Type"); } } private Hl7.Fhir.Model.Coding _Type; /// <summary> /// Contract Signatory Party /// </summary> [FhirElement("party", Order=50)] [CLSCompliant(false)] [References("Organization","Patient","Practitioner","RelatedPerson")] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.ResourceReference Party { get { return _Party; } set { _Party = value; OnPropertyChanged("Party"); } } private Hl7.Fhir.Model.ResourceReference _Party; /// <summary> /// Contract Documentation Signature /// </summary> [FhirElement("signature", Order=60)] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.FhirString SignatureElement { get { return _SignatureElement; } set { _SignatureElement = value; OnPropertyChanged("SignatureElement"); } } private Hl7.Fhir.Model.FhirString _SignatureElement; /// <summary> /// Contract Documentation Signature /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [IgnoreDataMember] public string Signature { get { return SignatureElement != null ? SignatureElement.Value : null; } set { if (value == null) SignatureElement = null; else SignatureElement = new Hl7.Fhir.Model.FhirString(value); OnPropertyChanged("Signature"); } } public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as SignatoryComponent; if (dest == null) { throw new ArgumentException("Can only copy to an object of the same type", "other"); } base.CopyTo(dest); if(Type != null) dest.Type = (Hl7.Fhir.Model.Coding)Type.DeepCopy(); if(Party != null) dest.Party = (Hl7.Fhir.Model.ResourceReference)Party.DeepCopy(); if(SignatureElement != null) dest.SignatureElement = (Hl7.Fhir.Model.FhirString)SignatureElement.DeepCopy(); return dest; } public override IDeepCopyable DeepCopy() { return CopyTo(new SignatoryComponent()); } public override bool Matches(IDeepComparable other) { var otherT = other as SignatoryComponent; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(Type, otherT.Type)) return false; if( !DeepComparable.Matches(Party, otherT.Party)) return false; if( !DeepComparable.Matches(SignatureElement, otherT.SignatureElement)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as SignatoryComponent; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(Type, otherT.Type)) return false; if( !DeepComparable.IsExactly(Party, otherT.Party)) return false; if( !DeepComparable.IsExactly(SignatureElement, otherT.SignatureElement)) return false; return true; } [IgnoreDataMember] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (Type != null) yield return Type; if (Party != null) yield return Party; if (SignatureElement != null) yield return SignatureElement; } } [IgnoreDataMember] public override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (Type != null) yield return new ElementValue("type", Type); if (Party != null) yield return new ElementValue("party", Party); if (SignatureElement != null) yield return new ElementValue("signature", SignatureElement); } } } /// <summary> /// Contract Term List /// </summary> [Serializable] [DataContract] [FhirType("Contract#Term", IsNestedType=true)] public partial class TermComponent : Hl7.Fhir.Model.BackboneElement { /// <summary> /// FHIR Type Name /// </summary> public override string TypeName { get { return "Contract#Term"; } } /// <summary> /// Contract Term identifier /// </summary> [FhirElement("identifier", InSummary=true, Order=40)] [DataMember] public Hl7.Fhir.Model.Identifier Identifier { get { return _Identifier; } set { _Identifier = value; OnPropertyChanged("Identifier"); } } private Hl7.Fhir.Model.Identifier _Identifier; /// <summary> /// Contract Term Issue Date Time /// </summary> [FhirElement("issued", InSummary=true, Order=50)] [DataMember] public Hl7.Fhir.Model.FhirDateTime IssuedElement { get { return _IssuedElement; } set { _IssuedElement = value; OnPropertyChanged("IssuedElement"); } } private Hl7.Fhir.Model.FhirDateTime _IssuedElement; /// <summary> /// Contract Term Issue Date Time /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [IgnoreDataMember] public string Issued { get { return IssuedElement != null ? IssuedElement.Value : null; } set { if (value == null) IssuedElement = null; else IssuedElement = new Hl7.Fhir.Model.FhirDateTime(value); OnPropertyChanged("Issued"); } } /// <summary> /// Contract Term Effective Time /// </summary> [FhirElement("applies", InSummary=true, Order=60)] [DataMember] public Hl7.Fhir.Model.Period Applies { get { return _Applies; } set { _Applies = value; OnPropertyChanged("Applies"); } } private Hl7.Fhir.Model.Period _Applies; /// <summary> /// Contract Term Type /// </summary> [FhirElement("type", Order=70)] [DataMember] public Hl7.Fhir.Model.CodeableConcept Type { get { return _Type; } set { _Type = value; OnPropertyChanged("Type"); } } private Hl7.Fhir.Model.CodeableConcept _Type; /// <summary> /// Contract Term Subtype /// </summary> [FhirElement("subType", Order=80)] [DataMember] public Hl7.Fhir.Model.CodeableConcept SubType { get { return _SubType; } set { _SubType = value; OnPropertyChanged("SubType"); } } private Hl7.Fhir.Model.CodeableConcept _SubType; /// <summary> /// Subject of this Contract Term /// </summary> [FhirElement("subject", Order=90)] [CLSCompliant(false)] [References("Resource")] [DataMember] public Hl7.Fhir.Model.ResourceReference Subject { get { return _Subject; } set { _Subject = value; OnPropertyChanged("Subject"); } } private Hl7.Fhir.Model.ResourceReference _Subject; /// <summary> /// Contract Term Action /// </summary> [FhirElement("action", Order=100)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.CodeableConcept> Action { get { if(_Action==null) _Action = new List<Hl7.Fhir.Model.CodeableConcept>(); return _Action; } set { _Action = value; OnPropertyChanged("Action"); } } private List<Hl7.Fhir.Model.CodeableConcept> _Action; /// <summary> /// Contract Term Action Reason /// </summary> [FhirElement("actionReason", Order=110)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.CodeableConcept> ActionReason { get { if(_ActionReason==null) _ActionReason = new List<Hl7.Fhir.Model.CodeableConcept>(); return _ActionReason; } set { _ActionReason = value; OnPropertyChanged("ActionReason"); } } private List<Hl7.Fhir.Model.CodeableConcept> _ActionReason; /// <summary> /// Contract Term Actor List /// </summary> [FhirElement("actor", Order=120)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.Contract.TermActorComponent> Actor { get { if(_Actor==null) _Actor = new List<Hl7.Fhir.Model.Contract.TermActorComponent>(); return _Actor; } set { _Actor = value; OnPropertyChanged("Actor"); } } private List<Hl7.Fhir.Model.Contract.TermActorComponent> _Actor; /// <summary> /// Human readable Contract term text /// </summary> [FhirElement("text", Order=130)] [DataMember] public Hl7.Fhir.Model.FhirString TextElement { get { return _TextElement; } set { _TextElement = value; OnPropertyChanged("TextElement"); } } private Hl7.Fhir.Model.FhirString _TextElement; /// <summary> /// Human readable Contract term text /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [IgnoreDataMember] public string Text { get { return TextElement != null ? TextElement.Value : null; } set { if (value == null) TextElement = null; else TextElement = new Hl7.Fhir.Model.FhirString(value); OnPropertyChanged("Text"); } } /// <summary> /// Contract Term Valued Item /// </summary> [FhirElement("valuedItem", Order=140)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.Contract.TermValuedItemComponent> ValuedItem { get { if(_ValuedItem==null) _ValuedItem = new List<Hl7.Fhir.Model.Contract.TermValuedItemComponent>(); return _ValuedItem; } set { _ValuedItem = value; OnPropertyChanged("ValuedItem"); } } private List<Hl7.Fhir.Model.Contract.TermValuedItemComponent> _ValuedItem; /// <summary> /// Nested Contract Term Group /// </summary> [FhirElement("group", Order=150)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.Contract.TermComponent> Group { get { if(_Group==null) _Group = new List<Hl7.Fhir.Model.Contract.TermComponent>(); return _Group; } set { _Group = value; OnPropertyChanged("Group"); } } private List<Hl7.Fhir.Model.Contract.TermComponent> _Group; public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as TermComponent; if (dest == null) { throw new ArgumentException("Can only copy to an object of the same type", "other"); } base.CopyTo(dest); if(Identifier != null) dest.Identifier = (Hl7.Fhir.Model.Identifier)Identifier.DeepCopy(); if(IssuedElement != null) dest.IssuedElement = (Hl7.Fhir.Model.FhirDateTime)IssuedElement.DeepCopy(); if(Applies != null) dest.Applies = (Hl7.Fhir.Model.Period)Applies.DeepCopy(); if(Type != null) dest.Type = (Hl7.Fhir.Model.CodeableConcept)Type.DeepCopy(); if(SubType != null) dest.SubType = (Hl7.Fhir.Model.CodeableConcept)SubType.DeepCopy(); if(Subject != null) dest.Subject = (Hl7.Fhir.Model.ResourceReference)Subject.DeepCopy(); if(Action != null) dest.Action = new List<Hl7.Fhir.Model.CodeableConcept>(Action.DeepCopy()); if(ActionReason != null) dest.ActionReason = new List<Hl7.Fhir.Model.CodeableConcept>(ActionReason.DeepCopy()); if(Actor != null) dest.Actor = new List<Hl7.Fhir.Model.Contract.TermActorComponent>(Actor.DeepCopy()); if(TextElement != null) dest.TextElement = (Hl7.Fhir.Model.FhirString)TextElement.DeepCopy(); if(ValuedItem != null) dest.ValuedItem = new List<Hl7.Fhir.Model.Contract.TermValuedItemComponent>(ValuedItem.DeepCopy()); if(Group != null) dest.Group = new List<Hl7.Fhir.Model.Contract.TermComponent>(Group.DeepCopy()); return dest; } public override IDeepCopyable DeepCopy() { return CopyTo(new TermComponent()); } public override bool Matches(IDeepComparable other) { var otherT = other as TermComponent; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(Identifier, otherT.Identifier)) return false; if( !DeepComparable.Matches(IssuedElement, otherT.IssuedElement)) return false; if( !DeepComparable.Matches(Applies, otherT.Applies)) return false; if( !DeepComparable.Matches(Type, otherT.Type)) return false; if( !DeepComparable.Matches(SubType, otherT.SubType)) return false; if( !DeepComparable.Matches(Subject, otherT.Subject)) return false; if( !DeepComparable.Matches(Action, otherT.Action)) return false; if( !DeepComparable.Matches(ActionReason, otherT.ActionReason)) return false; if( !DeepComparable.Matches(Actor, otherT.Actor)) return false; if( !DeepComparable.Matches(TextElement, otherT.TextElement)) return false; if( !DeepComparable.Matches(ValuedItem, otherT.ValuedItem)) return false; if( !DeepComparable.Matches(Group, otherT.Group)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as TermComponent; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(Identifier, otherT.Identifier)) return false; if( !DeepComparable.IsExactly(IssuedElement, otherT.IssuedElement)) return false; if( !DeepComparable.IsExactly(Applies, otherT.Applies)) return false; if( !DeepComparable.IsExactly(Type, otherT.Type)) return false; if( !DeepComparable.IsExactly(SubType, otherT.SubType)) return false; if( !DeepComparable.IsExactly(Subject, otherT.Subject)) return false; if( !DeepComparable.IsExactly(Action, otherT.Action)) return false; if( !DeepComparable.IsExactly(ActionReason, otherT.ActionReason)) return false; if( !DeepComparable.IsExactly(Actor, otherT.Actor)) return false; if( !DeepComparable.IsExactly(TextElement, otherT.TextElement)) return false; if( !DeepComparable.IsExactly(ValuedItem, otherT.ValuedItem)) return false; if( !DeepComparable.IsExactly(Group, otherT.Group)) return false; return true; } [IgnoreDataMember] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (Identifier != null) yield return Identifier; if (IssuedElement != null) yield return IssuedElement; if (Applies != null) yield return Applies; if (Type != null) yield return Type; if (SubType != null) yield return SubType; if (Subject != null) yield return Subject; foreach (var elem in Action) { if (elem != null) yield return elem; } foreach (var elem in ActionReason) { if (elem != null) yield return elem; } foreach (var elem in Actor) { if (elem != null) yield return elem; } if (TextElement != null) yield return TextElement; foreach (var elem in ValuedItem) { if (elem != null) yield return elem; } foreach (var elem in Group) { if (elem != null) yield return elem; } } } [IgnoreDataMember] public override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (Identifier != null) yield return new ElementValue("identifier", Identifier); if (IssuedElement != null) yield return new ElementValue("issued", IssuedElement); if (Applies != null) yield return new ElementValue("applies", Applies); if (Type != null) yield return new ElementValue("type", Type); if (SubType != null) yield return new ElementValue("subType", SubType); if (Subject != null) yield return new ElementValue("subject", Subject); foreach (var elem in Action) { if (elem != null) yield return new ElementValue("action", elem); } foreach (var elem in ActionReason) { if (elem != null) yield return new ElementValue("actionReason", elem); } foreach (var elem in Actor) { if (elem != null) yield return new ElementValue("actor", elem); } if (TextElement != null) yield return new ElementValue("text", TextElement); foreach (var elem in ValuedItem) { if (elem != null) yield return new ElementValue("valuedItem", elem); } foreach (var elem in Group) { if (elem != null) yield return new ElementValue("group", elem); } } } } /// <summary> /// Contract Term Actor List /// </summary> [Serializable] [DataContract] [FhirType("Contract#TermActor", IsNestedType=true)] public partial class TermActorComponent : Hl7.Fhir.Model.BackboneElement { /// <summary> /// FHIR Type Name /// </summary> public override string TypeName { get { return "Contract#TermActor"; } } /// <summary> /// Contract Term Actor /// </summary> [FhirElement("entity", Order=40)] [CLSCompliant(false)] [References("Contract","Device","Group","Location","Organization","Patient","Practitioner","RelatedPerson","Substance")] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.ResourceReference Entity { get { return _Entity; } set { _Entity = value; OnPropertyChanged("Entity"); } } private Hl7.Fhir.Model.ResourceReference _Entity; /// <summary> /// Contract Term Actor Role /// </summary> [FhirElement("role", Order=50)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.CodeableConcept> Role { get { if(_Role==null) _Role = new List<Hl7.Fhir.Model.CodeableConcept>(); return _Role; } set { _Role = value; OnPropertyChanged("Role"); } } private List<Hl7.Fhir.Model.CodeableConcept> _Role; public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as TermActorComponent; if (dest == null) { throw new ArgumentException("Can only copy to an object of the same type", "other"); } base.CopyTo(dest); if(Entity != null) dest.Entity = (Hl7.Fhir.Model.ResourceReference)Entity.DeepCopy(); if(Role != null) dest.Role = new List<Hl7.Fhir.Model.CodeableConcept>(Role.DeepCopy()); return dest; } public override IDeepCopyable DeepCopy() { return CopyTo(new TermActorComponent()); } public override bool Matches(IDeepComparable other) { var otherT = other as TermActorComponent; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(Entity, otherT.Entity)) return false; if( !DeepComparable.Matches(Role, otherT.Role)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as TermActorComponent; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(Entity, otherT.Entity)) return false; if( !DeepComparable.IsExactly(Role, otherT.Role)) return false; return true; } [IgnoreDataMember] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (Entity != null) yield return Entity; foreach (var elem in Role) { if (elem != null) yield return elem; } } } [IgnoreDataMember] public override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (Entity != null) yield return new ElementValue("entity", Entity); foreach (var elem in Role) { if (elem != null) yield return new ElementValue("role", elem); } } } } /// <summary> /// Contract Term Valued Item /// </summary> [Serializable] [DataContract] [FhirType("Contract#TermValuedItem", IsNestedType=true)] public partial class TermValuedItemComponent : Hl7.Fhir.Model.BackboneElement { /// <summary> /// FHIR Type Name /// </summary> public override string TypeName { get { return "Contract#TermValuedItem"; } } /// <summary> /// Contract Term Valued Item Type /// </summary> [FhirElement("entity", Order=40, Choice=ChoiceType.DatatypeChoice)] [CLSCompliant(false)] [AllowedTypes(typeof(Hl7.Fhir.Model.CodeableConcept),typeof(Hl7.Fhir.Model.ResourceReference))] [DataMember] public Hl7.Fhir.Model.DataType Entity { get { return _Entity; } set { _Entity = value; OnPropertyChanged("Entity"); } } private Hl7.Fhir.Model.DataType _Entity; /// <summary> /// Contract Term Valued Item Identifier /// </summary> [FhirElement("identifier", Order=50)] [DataMember] public Hl7.Fhir.Model.Identifier Identifier { get { return _Identifier; } set { _Identifier = value; OnPropertyChanged("Identifier"); } } private Hl7.Fhir.Model.Identifier _Identifier; /// <summary> /// Contract Term Valued Item Effective Tiem /// </summary> [FhirElement("effectiveTime", Order=60)] [DataMember] public Hl7.Fhir.Model.FhirDateTime EffectiveTimeElement { get { return _EffectiveTimeElement; } set { _EffectiveTimeElement = value; OnPropertyChanged("EffectiveTimeElement"); } } private Hl7.Fhir.Model.FhirDateTime _EffectiveTimeElement; /// <summary> /// Contract Term Valued Item Effective Tiem /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [IgnoreDataMember] public string EffectiveTime { get { return EffectiveTimeElement != null ? EffectiveTimeElement.Value : null; } set { if (value == null) EffectiveTimeElement = null; else EffectiveTimeElement = new Hl7.Fhir.Model.FhirDateTime(value); OnPropertyChanged("EffectiveTime"); } } /// <summary> /// Contract Term Valued Item Count /// </summary> [FhirElement("quantity", Order=70)] [DataMember] public Hl7.Fhir.Model.Quantity Quantity { get { return _Quantity; } set { _Quantity = value; OnPropertyChanged("Quantity"); } } private Hl7.Fhir.Model.Quantity _Quantity; /// <summary> /// Contract Term Valued Item fee, charge, or cost /// </summary> [FhirElement("unitPrice", Order=80)] [DataMember] public Hl7.Fhir.Model.Quantity UnitPrice { get { return _UnitPrice; } set { _UnitPrice = value; OnPropertyChanged("UnitPrice"); } } private Hl7.Fhir.Model.Quantity _UnitPrice; /// <summary> /// Contract Term Valued Item Price Scaling Factor /// </summary> [FhirElement("factor", Order=90)] [DataMember] public Hl7.Fhir.Model.FhirDecimal FactorElement { get { return _FactorElement; } set { _FactorElement = value; OnPropertyChanged("FactorElement"); } } private Hl7.Fhir.Model.FhirDecimal _FactorElement; /// <summary> /// Contract Term Valued Item Price Scaling Factor /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [IgnoreDataMember] public decimal? Factor { get { return FactorElement != null ? FactorElement.Value : null; } set { if (value == null) FactorElement = null; else FactorElement = new Hl7.Fhir.Model.FhirDecimal(value); OnPropertyChanged("Factor"); } } /// <summary> /// Contract Term Valued Item Difficulty Scaling Factor /// </summary> [FhirElement("points", Order=100)] [DataMember] public Hl7.Fhir.Model.FhirDecimal PointsElement { get { return _PointsElement; } set { _PointsElement = value; OnPropertyChanged("PointsElement"); } } private Hl7.Fhir.Model.FhirDecimal _PointsElement; /// <summary> /// Contract Term Valued Item Difficulty Scaling Factor /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [IgnoreDataMember] public decimal? Points { get { return PointsElement != null ? PointsElement.Value : null; } set { if (value == null) PointsElement = null; else PointsElement = new Hl7.Fhir.Model.FhirDecimal(value); OnPropertyChanged("Points"); } } /// <summary> /// Total Contract Term Valued Item Value /// </summary> [FhirElement("net", Order=110)] [DataMember] public Hl7.Fhir.Model.Quantity Net { get { return _Net; } set { _Net = value; OnPropertyChanged("Net"); } } private Hl7.Fhir.Model.Quantity _Net; public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as TermValuedItemComponent; if (dest == null) { throw new ArgumentException("Can only copy to an object of the same type", "other"); } base.CopyTo(dest); if(Entity != null) dest.Entity = (Hl7.Fhir.Model.DataType)Entity.DeepCopy(); if(Identifier != null) dest.Identifier = (Hl7.Fhir.Model.Identifier)Identifier.DeepCopy(); if(EffectiveTimeElement != null) dest.EffectiveTimeElement = (Hl7.Fhir.Model.FhirDateTime)EffectiveTimeElement.DeepCopy(); if(Quantity != null) dest.Quantity = (Hl7.Fhir.Model.Quantity)Quantity.DeepCopy(); if(UnitPrice != null) dest.UnitPrice = (Hl7.Fhir.Model.Quantity)UnitPrice.DeepCopy(); if(FactorElement != null) dest.FactorElement = (Hl7.Fhir.Model.FhirDecimal)FactorElement.DeepCopy(); if(PointsElement != null) dest.PointsElement = (Hl7.Fhir.Model.FhirDecimal)PointsElement.DeepCopy(); if(Net != null) dest.Net = (Hl7.Fhir.Model.Quantity)Net.DeepCopy(); return dest; } public override IDeepCopyable DeepCopy() { return CopyTo(new TermValuedItemComponent()); } public override bool Matches(IDeepComparable other) { var otherT = other as TermValuedItemComponent; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(Entity, otherT.Entity)) return false; if( !DeepComparable.Matches(Identifier, otherT.Identifier)) return false; if( !DeepComparable.Matches(EffectiveTimeElement, otherT.EffectiveTimeElement)) return false; if( !DeepComparable.Matches(Quantity, otherT.Quantity)) return false; if( !DeepComparable.Matches(UnitPrice, otherT.UnitPrice)) return false; if( !DeepComparable.Matches(FactorElement, otherT.FactorElement)) return false; if( !DeepComparable.Matches(PointsElement, otherT.PointsElement)) return false; if( !DeepComparable.Matches(Net, otherT.Net)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as TermValuedItemComponent; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(Entity, otherT.Entity)) return false; if( !DeepComparable.IsExactly(Identifier, otherT.Identifier)) return false; if( !DeepComparable.IsExactly(EffectiveTimeElement, otherT.EffectiveTimeElement)) return false; if( !DeepComparable.IsExactly(Quantity, otherT.Quantity)) return false; if( !DeepComparable.IsExactly(UnitPrice, otherT.UnitPrice)) return false; if( !DeepComparable.IsExactly(FactorElement, otherT.FactorElement)) return false; if( !DeepComparable.IsExactly(PointsElement, otherT.PointsElement)) return false; if( !DeepComparable.IsExactly(Net, otherT.Net)) return false; return true; } [IgnoreDataMember] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (Entity != null) yield return Entity; if (Identifier != null) yield return Identifier; if (EffectiveTimeElement != null) yield return EffectiveTimeElement; if (Quantity != null) yield return Quantity; if (UnitPrice != null) yield return UnitPrice; if (FactorElement != null) yield return FactorElement; if (PointsElement != null) yield return PointsElement; if (Net != null) yield return Net; } } [IgnoreDataMember] public override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (Entity != null) yield return new ElementValue("entity", Entity); if (Identifier != null) yield return new ElementValue("identifier", Identifier); if (EffectiveTimeElement != null) yield return new ElementValue("effectiveTime", EffectiveTimeElement); if (Quantity != null) yield return new ElementValue("quantity", Quantity); if (UnitPrice != null) yield return new ElementValue("unitPrice", UnitPrice); if (FactorElement != null) yield return new ElementValue("factor", FactorElement); if (PointsElement != null) yield return new ElementValue("points", PointsElement); if (Net != null) yield return new ElementValue("net", Net); } } } /// <summary> /// Contract Friendly Language /// </summary> [Serializable] [DataContract] [FhirType("Contract#FriendlyLanguage", IsNestedType=true)] public partial class FriendlyLanguageComponent : Hl7.Fhir.Model.BackboneElement { /// <summary> /// FHIR Type Name /// </summary> public override string TypeName { get { return "Contract#FriendlyLanguage"; } } /// <summary> /// Easily comprehended representation of this Contract /// </summary> [FhirElement("content", Order=40, Choice=ChoiceType.DatatypeChoice)] [CLSCompliant(false)] [AllowedTypes(typeof(Hl7.Fhir.Model.Attachment),typeof(Hl7.Fhir.Model.ResourceReference))] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.DataType Content { get { return _Content; } set { _Content = value; OnPropertyChanged("Content"); } } private Hl7.Fhir.Model.DataType _Content; public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as FriendlyLanguageComponent; if (dest == null) { throw new ArgumentException("Can only copy to an object of the same type", "other"); } base.CopyTo(dest); if(Content != null) dest.Content = (Hl7.Fhir.Model.DataType)Content.DeepCopy(); return dest; } public override IDeepCopyable DeepCopy() { return CopyTo(new FriendlyLanguageComponent()); } public override bool Matches(IDeepComparable other) { var otherT = other as FriendlyLanguageComponent; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(Content, otherT.Content)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as FriendlyLanguageComponent; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(Content, otherT.Content)) return false; return true; } [IgnoreDataMember] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (Content != null) yield return Content; } } [IgnoreDataMember] public override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (Content != null) yield return new ElementValue("content", Content); } } } /// <summary> /// Contract Legal Language /// </summary> [Serializable] [DataContract] [FhirType("Contract#LegalLanguage", IsNestedType=true)] public partial class LegalLanguageComponent : Hl7.Fhir.Model.BackboneElement { /// <summary> /// FHIR Type Name /// </summary> public override string TypeName { get { return "Contract#LegalLanguage"; } } /// <summary> /// Contract Legal Text /// </summary> [FhirElement("content", Order=40, Choice=ChoiceType.DatatypeChoice)] [CLSCompliant(false)] [AllowedTypes(typeof(Hl7.Fhir.Model.Attachment),typeof(Hl7.Fhir.Model.ResourceReference))] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.DataType Content { get { return _Content; } set { _Content = value; OnPropertyChanged("Content"); } } private Hl7.Fhir.Model.DataType _Content; public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as LegalLanguageComponent; if (dest == null) { throw new ArgumentException("Can only copy to an object of the same type", "other"); } base.CopyTo(dest); if(Content != null) dest.Content = (Hl7.Fhir.Model.DataType)Content.DeepCopy(); return dest; } public override IDeepCopyable DeepCopy() { return CopyTo(new LegalLanguageComponent()); } public override bool Matches(IDeepComparable other) { var otherT = other as LegalLanguageComponent; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(Content, otherT.Content)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as LegalLanguageComponent; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(Content, otherT.Content)) return false; return true; } [IgnoreDataMember] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (Content != null) yield return Content; } } [IgnoreDataMember] public override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (Content != null) yield return new ElementValue("content", Content); } } } /// <summary> /// Computable Contract Language /// </summary> [Serializable] [DataContract] [FhirType("Contract#ComputableLanguage", IsNestedType=true)] public partial class ComputableLanguageComponent : Hl7.Fhir.Model.BackboneElement { /// <summary> /// FHIR Type Name /// </summary> public override string TypeName { get { return "Contract#ComputableLanguage"; } } /// <summary> /// Computable Contract Rules /// </summary> [FhirElement("content", Order=40, Choice=ChoiceType.DatatypeChoice)] [CLSCompliant(false)] [AllowedTypes(typeof(Hl7.Fhir.Model.Attachment),typeof(Hl7.Fhir.Model.ResourceReference))] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.DataType Content { get { return _Content; } set { _Content = value; OnPropertyChanged("Content"); } } private Hl7.Fhir.Model.DataType _Content; public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as ComputableLanguageComponent; if (dest == null) { throw new ArgumentException("Can only copy to an object of the same type", "other"); } base.CopyTo(dest); if(Content != null) dest.Content = (Hl7.Fhir.Model.DataType)Content.DeepCopy(); return dest; } public override IDeepCopyable DeepCopy() { return CopyTo(new ComputableLanguageComponent()); } public override bool Matches(IDeepComparable other) { var otherT = other as ComputableLanguageComponent; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(Content, otherT.Content)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as ComputableLanguageComponent; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(Content, otherT.Content)) return false; return true; } [IgnoreDataMember] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (Content != null) yield return Content; } } [IgnoreDataMember] public override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (Content != null) yield return new ElementValue("content", Content); } } } /// <summary> /// Contract identifier /// </summary> [FhirElement("identifier", InSummary=true, Order=90)] [DataMember] public Hl7.Fhir.Model.Identifier Identifier { get { return _Identifier; } set { _Identifier = value; OnPropertyChanged("Identifier"); } } private Hl7.Fhir.Model.Identifier _Identifier; /// <summary> /// When this Contract was issued /// </summary> [FhirElement("issued", InSummary=true, Order=100)] [DataMember] public Hl7.Fhir.Model.FhirDateTime IssuedElement { get { return _IssuedElement; } set { _IssuedElement = value; OnPropertyChanged("IssuedElement"); } } private Hl7.Fhir.Model.FhirDateTime _IssuedElement; /// <summary> /// When this Contract was issued /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [IgnoreDataMember] public string Issued { get { return IssuedElement != null ? IssuedElement.Value : null; } set { if (value == null) IssuedElement = null; else IssuedElement = new Hl7.Fhir.Model.FhirDateTime(value); OnPropertyChanged("Issued"); } } /// <summary> /// Effective time /// </summary> [FhirElement("applies", InSummary=true, Order=110)] [DataMember] public Hl7.Fhir.Model.Period Applies { get { return _Applies; } set { _Applies = value; OnPropertyChanged("Applies"); } } private Hl7.Fhir.Model.Period _Applies; /// <summary> /// Subject of this Contract /// </summary> [FhirElement("subject", InSummary=true, Order=120)] [CLSCompliant(false)] [References("Resource")] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.ResourceReference> Subject { get { if(_Subject==null) _Subject = new List<Hl7.Fhir.Model.ResourceReference>(); return _Subject; } set { _Subject = value; OnPropertyChanged("Subject"); } } private List<Hl7.Fhir.Model.ResourceReference> _Subject; /// <summary> /// Authority under which this Contract has standing /// </summary> [FhirElement("authority", Order=130)] [CLSCompliant(false)] [References("Organization")] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.ResourceReference> Authority { get { if(_Authority==null) _Authority = new List<Hl7.Fhir.Model.ResourceReference>(); return _Authority; } set { _Authority = value; OnPropertyChanged("Authority"); } } private List<Hl7.Fhir.Model.ResourceReference> _Authority; /// <summary> /// Domain in which this Contract applies /// </summary> [FhirElement("domain", Order=140)] [CLSCompliant(false)] [References("Location")] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.ResourceReference> Domain { get { if(_Domain==null) _Domain = new List<Hl7.Fhir.Model.ResourceReference>(); return _Domain; } set { _Domain = value; OnPropertyChanged("Domain"); } } private List<Hl7.Fhir.Model.ResourceReference> _Domain; /// <summary> /// Contract Tyoe /// </summary> [FhirElement("type", InSummary=true, Order=150)] [DataMember] public Hl7.Fhir.Model.CodeableConcept Type { get { return _Type; } set { _Type = value; OnPropertyChanged("Type"); } } private Hl7.Fhir.Model.CodeableConcept _Type; /// <summary> /// Contract Subtype /// </summary> [FhirElement("subType", InSummary=true, Order=160)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.CodeableConcept> SubType { get { if(_SubType==null) _SubType = new List<Hl7.Fhir.Model.CodeableConcept>(); return _SubType; } set { _SubType = value; OnPropertyChanged("SubType"); } } private List<Hl7.Fhir.Model.CodeableConcept> _SubType; /// <summary> /// Contract Action /// </summary> [FhirElement("action", Order=170)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.CodeableConcept> Action { get { if(_Action==null) _Action = new List<Hl7.Fhir.Model.CodeableConcept>(); return _Action; } set { _Action = value; OnPropertyChanged("Action"); } } private List<Hl7.Fhir.Model.CodeableConcept> _Action; /// <summary> /// Contract Action Reason /// </summary> [FhirElement("actionReason", Order=180)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.CodeableConcept> ActionReason { get { if(_ActionReason==null) _ActionReason = new List<Hl7.Fhir.Model.CodeableConcept>(); return _ActionReason; } set { _ActionReason = value; OnPropertyChanged("ActionReason"); } } private List<Hl7.Fhir.Model.CodeableConcept> _ActionReason; /// <summary> /// Contract Actor /// </summary> [FhirElement("actor", Order=190)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.Contract.ActorComponent> Actor { get { if(_Actor==null) _Actor = new List<Hl7.Fhir.Model.Contract.ActorComponent>(); return _Actor; } set { _Actor = value; OnPropertyChanged("Actor"); } } private List<Hl7.Fhir.Model.Contract.ActorComponent> _Actor; /// <summary> /// Contract Valued Item /// </summary> [FhirElement("valuedItem", Order=200)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.Contract.ValuedItemComponent> ValuedItem { get { if(_ValuedItem==null) _ValuedItem = new List<Hl7.Fhir.Model.Contract.ValuedItemComponent>(); return _ValuedItem; } set { _ValuedItem = value; OnPropertyChanged("ValuedItem"); } } private List<Hl7.Fhir.Model.Contract.ValuedItemComponent> _ValuedItem; /// <summary> /// Contract Signer /// </summary> [FhirElement("signer", Order=210)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.Contract.SignatoryComponent> Signer { get { if(_Signer==null) _Signer = new List<Hl7.Fhir.Model.Contract.SignatoryComponent>(); return _Signer; } set { _Signer = value; OnPropertyChanged("Signer"); } } private List<Hl7.Fhir.Model.Contract.SignatoryComponent> _Signer; /// <summary> /// Contract Term List /// </summary> [FhirElement("term", Order=220)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.Contract.TermComponent> Term { get { if(_Term==null) _Term = new List<Hl7.Fhir.Model.Contract.TermComponent>(); return _Term; } set { _Term = value; OnPropertyChanged("Term"); } } private List<Hl7.Fhir.Model.Contract.TermComponent> _Term; /// <summary> /// Binding Contract /// </summary> [FhirElement("binding", Order=230, Choice=ChoiceType.DatatypeChoice)] [CLSCompliant(false)] [AllowedTypes(typeof(Hl7.Fhir.Model.Attachment),typeof(Hl7.Fhir.Model.ResourceReference))] [DataMember] public Hl7.Fhir.Model.DataType Binding { get { return _Binding; } set { _Binding = value; OnPropertyChanged("Binding"); } } private Hl7.Fhir.Model.DataType _Binding; /// <summary> /// Contract Friendly Language /// </summary> [FhirElement("friendly", Order=240)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.Contract.FriendlyLanguageComponent> Friendly { get { if(_Friendly==null) _Friendly = new List<Hl7.Fhir.Model.Contract.FriendlyLanguageComponent>(); return _Friendly; } set { _Friendly = value; OnPropertyChanged("Friendly"); } } private List<Hl7.Fhir.Model.Contract.FriendlyLanguageComponent> _Friendly; /// <summary> /// Contract Legal Language /// </summary> [FhirElement("legal", Order=250)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.Contract.LegalLanguageComponent> Legal { get { if(_Legal==null) _Legal = new List<Hl7.Fhir.Model.Contract.LegalLanguageComponent>(); return _Legal; } set { _Legal = value; OnPropertyChanged("Legal"); } } private List<Hl7.Fhir.Model.Contract.LegalLanguageComponent> _Legal; /// <summary> /// Computable Contract Language /// </summary> [FhirElement("rule", Order=260)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.Contract.ComputableLanguageComponent> Rule { get { if(_Rule==null) _Rule = new List<Hl7.Fhir.Model.Contract.ComputableLanguageComponent>(); return _Rule; } set { _Rule = value; OnPropertyChanged("Rule"); } } private List<Hl7.Fhir.Model.Contract.ComputableLanguageComponent> _Rule; public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as Contract; if (dest == null) { throw new ArgumentException("Can only copy to an object of the same type", "other"); } base.CopyTo(dest); if(Identifier != null) dest.Identifier = (Hl7.Fhir.Model.Identifier)Identifier.DeepCopy(); if(IssuedElement != null) dest.IssuedElement = (Hl7.Fhir.Model.FhirDateTime)IssuedElement.DeepCopy(); if(Applies != null) dest.Applies = (Hl7.Fhir.Model.Period)Applies.DeepCopy(); if(Subject != null) dest.Subject = new List<Hl7.Fhir.Model.ResourceReference>(Subject.DeepCopy()); if(Authority != null) dest.Authority = new List<Hl7.Fhir.Model.ResourceReference>(Authority.DeepCopy()); if(Domain != null) dest.Domain = new List<Hl7.Fhir.Model.ResourceReference>(Domain.DeepCopy()); if(Type != null) dest.Type = (Hl7.Fhir.Model.CodeableConcept)Type.DeepCopy(); if(SubType != null) dest.SubType = new List<Hl7.Fhir.Model.CodeableConcept>(SubType.DeepCopy()); if(Action != null) dest.Action = new List<Hl7.Fhir.Model.CodeableConcept>(Action.DeepCopy()); if(ActionReason != null) dest.ActionReason = new List<Hl7.Fhir.Model.CodeableConcept>(ActionReason.DeepCopy()); if(Actor != null) dest.Actor = new List<Hl7.Fhir.Model.Contract.ActorComponent>(Actor.DeepCopy()); if(ValuedItem != null) dest.ValuedItem = new List<Hl7.Fhir.Model.Contract.ValuedItemComponent>(ValuedItem.DeepCopy()); if(Signer != null) dest.Signer = new List<Hl7.Fhir.Model.Contract.SignatoryComponent>(Signer.DeepCopy()); if(Term != null) dest.Term = new List<Hl7.Fhir.Model.Contract.TermComponent>(Term.DeepCopy()); if(Binding != null) dest.Binding = (Hl7.Fhir.Model.DataType)Binding.DeepCopy(); if(Friendly != null) dest.Friendly = new List<Hl7.Fhir.Model.Contract.FriendlyLanguageComponent>(Friendly.DeepCopy()); if(Legal != null) dest.Legal = new List<Hl7.Fhir.Model.Contract.LegalLanguageComponent>(Legal.DeepCopy()); if(Rule != null) dest.Rule = new List<Hl7.Fhir.Model.Contract.ComputableLanguageComponent>(Rule.DeepCopy()); return dest; } public override IDeepCopyable DeepCopy() { return CopyTo(new Contract()); } public override bool Matches(IDeepComparable other) { var otherT = other as Contract; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(Identifier, otherT.Identifier)) return false; if( !DeepComparable.Matches(IssuedElement, otherT.IssuedElement)) return false; if( !DeepComparable.Matches(Applies, otherT.Applies)) return false; if( !DeepComparable.Matches(Subject, otherT.Subject)) return false; if( !DeepComparable.Matches(Authority, otherT.Authority)) return false; if( !DeepComparable.Matches(Domain, otherT.Domain)) return false; if( !DeepComparable.Matches(Type, otherT.Type)) return false; if( !DeepComparable.Matches(SubType, otherT.SubType)) return false; if( !DeepComparable.Matches(Action, otherT.Action)) return false; if( !DeepComparable.Matches(ActionReason, otherT.ActionReason)) return false; if( !DeepComparable.Matches(Actor, otherT.Actor)) return false; if( !DeepComparable.Matches(ValuedItem, otherT.ValuedItem)) return false; if( !DeepComparable.Matches(Signer, otherT.Signer)) return false; if( !DeepComparable.Matches(Term, otherT.Term)) return false; if( !DeepComparable.Matches(Binding, otherT.Binding)) return false; if( !DeepComparable.Matches(Friendly, otherT.Friendly)) return false; if( !DeepComparable.Matches(Legal, otherT.Legal)) return false; if( !DeepComparable.Matches(Rule, otherT.Rule)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as Contract; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(Identifier, otherT.Identifier)) return false; if( !DeepComparable.IsExactly(IssuedElement, otherT.IssuedElement)) return false; if( !DeepComparable.IsExactly(Applies, otherT.Applies)) return false; if( !DeepComparable.IsExactly(Subject, otherT.Subject)) return false; if( !DeepComparable.IsExactly(Authority, otherT.Authority)) return false; if( !DeepComparable.IsExactly(Domain, otherT.Domain)) return false; if( !DeepComparable.IsExactly(Type, otherT.Type)) return false; if( !DeepComparable.IsExactly(SubType, otherT.SubType)) return false; if( !DeepComparable.IsExactly(Action, otherT.Action)) return false; if( !DeepComparable.IsExactly(ActionReason, otherT.ActionReason)) return false; if( !DeepComparable.IsExactly(Actor, otherT.Actor)) return false; if( !DeepComparable.IsExactly(ValuedItem, otherT.ValuedItem)) return false; if( !DeepComparable.IsExactly(Signer, otherT.Signer)) return false; if( !DeepComparable.IsExactly(Term, otherT.Term)) return false; if( !DeepComparable.IsExactly(Binding, otherT.Binding)) return false; if( !DeepComparable.IsExactly(Friendly, otherT.Friendly)) return false; if( !DeepComparable.IsExactly(Legal, otherT.Legal)) return false; if( !DeepComparable.IsExactly(Rule, otherT.Rule)) return false; return true; } [IgnoreDataMember] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (Identifier != null) yield return Identifier; if (IssuedElement != null) yield return IssuedElement; if (Applies != null) yield return Applies; foreach (var elem in Subject) { if (elem != null) yield return elem; } foreach (var elem in Authority) { if (elem != null) yield return elem; } foreach (var elem in Domain) { if (elem != null) yield return elem; } if (Type != null) yield return Type; foreach (var elem in SubType) { if (elem != null) yield return elem; } foreach (var elem in Action) { if (elem != null) yield return elem; } foreach (var elem in ActionReason) { if (elem != null) yield return elem; } foreach (var elem in Actor) { if (elem != null) yield return elem; } foreach (var elem in ValuedItem) { if (elem != null) yield return elem; } foreach (var elem in Signer) { if (elem != null) yield return elem; } foreach (var elem in Term) { if (elem != null) yield return elem; } if (Binding != null) yield return Binding; foreach (var elem in Friendly) { if (elem != null) yield return elem; } foreach (var elem in Legal) { if (elem != null) yield return elem; } foreach (var elem in Rule) { if (elem != null) yield return elem; } } } [IgnoreDataMember] public override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (Identifier != null) yield return new ElementValue("identifier", Identifier); if (IssuedElement != null) yield return new ElementValue("issued", IssuedElement); if (Applies != null) yield return new ElementValue("applies", Applies); foreach (var elem in Subject) { if (elem != null) yield return new ElementValue("subject", elem); } foreach (var elem in Authority) { if (elem != null) yield return new ElementValue("authority", elem); } foreach (var elem in Domain) { if (elem != null) yield return new ElementValue("domain", elem); } if (Type != null) yield return new ElementValue("type", Type); foreach (var elem in SubType) { if (elem != null) yield return new ElementValue("subType", elem); } foreach (var elem in Action) { if (elem != null) yield return new ElementValue("action", elem); } foreach (var elem in ActionReason) { if (elem != null) yield return new ElementValue("actionReason", elem); } foreach (var elem in Actor) { if (elem != null) yield return new ElementValue("actor", elem); } foreach (var elem in ValuedItem) { if (elem != null) yield return new ElementValue("valuedItem", elem); } foreach (var elem in Signer) { if (elem != null) yield return new ElementValue("signer", elem); } foreach (var elem in Term) { if (elem != null) yield return new ElementValue("term", elem); } if (Binding != null) yield return new ElementValue("binding", Binding); foreach (var elem in Friendly) { if (elem != null) yield return new ElementValue("friendly", elem); } foreach (var elem in Legal) { if (elem != null) yield return new ElementValue("legal", elem); } foreach (var elem in Rule) { if (elem != null) yield return new ElementValue("rule", elem); } } } } } // end of file
36.2035
132
0.635574
[ "MIT" ]
FirelyTeam/fhir-codegen
generated/CSharpFirely2_R2/Generated/Contract.cs
72,407
C#
using Harmony12; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; using UnityEngine.UI; using UnityModManagerNet; using static UnityModManagerNet.UnityModManager; namespace BuriedTreasureDetector { public class Work { private static Work _instance; private static object _instance_Lock = new object(); public static Work Instance { get { if (_instance == null) { lock (_instance_Lock) { if (_instance == null) { _instance = new Work(); } } } return _instance; } } public void ChooseTimeWork() { //循环所有15个大地图 for (int baseWorldId = 0; baseWorldId < 15; baseWorldId++) { //循环所有地图里面的3个地区 foreach (int basePartId in DateFile.instance.baseWorldDate[baseWorldId].Keys) { // 判断当前地图是否有人力 //if (DateFile.instance.manpowerUseList.ContainsKey(basePartId)) if (DateFile.instance.worldMapWorkState.ContainsKey(basePartId)) { //获取当前地区的地图宽度 int mapWidth = int.Parse(DateFile.instance.partWorldMapDate[basePartId][98]); //循环所有地块 for (int placeId = 0; placeId < mapWidth * mapWidth; placeId++) { // 判断当前地块是否有人力 //if (DateFile.instance.manpowerUseList[basePartId].ContainsKey(placeId)) if (DateFile.instance.worldMapWorkState[basePartId].ContainsKey(placeId)) { // 采集类型 int workTyp = DateFile.instance.worldMapWorkState[basePartId][placeId] - 1; //最大资源 int maxResource = Mathf.Max(int.Parse(DateFile.instance.GetNewMapDate(basePartId, placeId, workTyp + 1)), 1); //当前资源 int nowResource = Mathf.Max(DateFile.instance.GetPlaceResource(basePartId, placeId)[workTyp], 0); if (maxResource >= 100 && maxResource.Equals(nowResource)) { ChooseTimeWork(basePartId, placeId, workTyp); } } } } } } } private void ChooseTimeWork(int choosePartId, int choosePlaceId, int chooseWorkTyp) { int num = DateFile.instance.GetPlaceResource(choosePartId, choosePlaceId)[chooseWorkTyp]; int num2 = (num >= 100) ? (num * 60 / 100) : (num * 40 / 100); num2 += UnityEngine.Random.Range(-num2 * 20 / 100, num2 * 20 / 100 + 1); int getItemId = WorldMapSystem.instance.GetTimeWorkItem(DateFile.instance.MianActorID(), choosePartId, choosePlaceId, chooseWorkTyp, -1, getItem: false, actorWork: true); int addResource = Mathf.Max(num2, 0); TimeWorkEnd(addResource, getItemId, choosePartId, choosePlaceId, chooseWorkTyp); } private static void TimeWorkEnd(int addResource, int getItemId, int choosePartId, int choosePlaceId, int chooseWorkTyp) { // 更新物品 if (getItemId != 0) { DateFile.instance.GetItem(DateFile.instance.MianActorID(), getItemId, 1, true, 0); } //更新地块信息 UIDate.instance.ChangePlaceResource(false, -25, choosePartId, choosePlaceId, chooseWorkTyp); int num = (DateFile.instance.worldResource == 0) ? 10 : 5; int num2 = (DateFile.instance.worldResource == 0) ? 4 : 2; // 更新太吾资源 UIDate.instance.ChangeResource(DateFile.instance.MianActorID(), chooseWorkTyp, (chooseWorkTyp == 5) ? (addResource * num) : (addResource * num2)); } } }
41.144231
182
0.5104
[ "MIT" ]
410998623/Taiwu_mods
BuriedTreasureDetector/Work.cs
4,455
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. #nullable disable using System.ComponentModel; namespace System.Windows.Forms { public class ColumnReorderedEventArgs : CancelEventArgs { public ColumnReorderedEventArgs(int oldDisplayIndex, int newDisplayIndex, ColumnHeader header) : base() { OldDisplayIndex = oldDisplayIndex; NewDisplayIndex = newDisplayIndex; Header = header; } public int OldDisplayIndex { get; } public int NewDisplayIndex { get; } public ColumnHeader Header { get; } } }
27.814815
111
0.684421
[ "MIT" ]
Amy-Li03/winforms
src/System.Windows.Forms/src/System/Windows/Forms/ColumnReorderedEventArgs.cs
753
C#
using ElasticUp.Helper; using Nest; using static ElasticUp.Validations.IndexValidations; using static ElasticUp.Validations.StringValidations; namespace ElasticUp.Operation.Alias { public class CreateAliasOperation : AbstractElasticUpOperation { protected string Alias; protected string IndexName; public CreateAliasOperation(string alias) { Alias = alias?.ToLowerInvariant(); } public virtual CreateAliasOperation OnIndex(string indexName) { IndexName = indexName?.ToLowerInvariant(); return this; } public override void Validate(IElasticClient elasticClient) { StringValidationsFor<CreateAliasOperation>() .IsNotBlank(Alias, RequiredMessage("Alias")) .IsNotBlank(IndexName, RequiredMessage("IndexName")); IndexValidationsFor<CreateAliasOperation>(elasticClient) .IndexExists(IndexName); } public override void Execute(IElasticClient elasticClient) { new AliasHelper(elasticClient).PutAliasOnIndex(Alias, IndexName); } } }
29.375
77
0.655319
[ "MIT" ]
XPCegeka/ElasticUp
ElasticUp/ElasticUp/Operation/Alias/CreateAliasOperation.cs
1,177
C#
/* Status: Solved Imported: 2020-05-02 12:48 By: Casper Url: https://app.codesignal.com/arcade/code-arcade/book-market/MX94DWTrwQw2gLrTi Description: You are implementing your own HTML editor. To make it more comfortable for developers you would like to add an auto-completion feature to it. Given the starting HTML tag, find the appropriate end tag which your editor should propose. If you are not familiar with HTML, consult with this note. Example For startTag = "<button type='button' disabled>", the output should be htmlEndTagByStartTag(startTag) = "</button>"; For startTag = "<i>", the output should be htmlEndTagByStartTag(startTag) = "</i>". Input/Output [execution time limit] 3 seconds (cs) [input] string startTag Guaranteed constraints: 3 ≤ startTag.length ≤ 75. [output] string */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace CodeSignalSolutions.TheCore.BookMarket { class htmlEndTagByStartTagClass { string htmlEndTagByStartTag(string startTag) { var regex = new Regex(@"<(\w+)\b"); var match = regex.Match(startTag); if (!match.Success) return ""; return "</" + match.Groups[1].Value + ">"; } } }
33.534884
89
0.636616
[ "Apache-2.0" ]
casper-a-hansen/CodeSignal
CodeSignalSolutions/TheCore/BookMarket/htmlEndTagByStartTagClass.cs
1,446
C#
using System; using System.Collections.Generic; using System.Linq; using Naveego.Sdk.Logging; using Naveego.Sdk.Plugins; using Newtonsoft.Json.Linq; namespace PluginAthenaHealth.API.Discover { public static partial class Discover { /// <summary> /// Gets the Naveego type from the provided records /// </summary> /// <param name="records"></param> /// <returns>The property type</returns> private static Dictionary<string, PropertyType> GetPropertyTypesFromRecords( List<Dictionary<string, object>> records) { try { // build up a dictionary of the count of each type for each property var discoveredTypes = new Dictionary<string, Dictionary<PropertyType, int>>(); foreach (var record in records) { foreach (var recordKey in record.Keys) { if (!discoveredTypes.ContainsKey(recordKey)) { discoveredTypes.Add(recordKey, new Dictionary<PropertyType, int> { {PropertyType.String, 0}, {PropertyType.Bool, 0}, {PropertyType.Integer, 0}, {PropertyType.Float, 0}, {PropertyType.Json, 0}, {PropertyType.Datetime, 0} }); } var value = record[recordKey]; if (value == null) continue; switch (value) { case bool _: discoveredTypes[recordKey][PropertyType.Bool]++; break; case long _: discoveredTypes[recordKey][PropertyType.Integer]++; break; case double _: discoveredTypes[recordKey][PropertyType.Float]++; break; case JToken _: discoveredTypes[recordKey][PropertyType.Json]++; break; default: { if (DateTime.TryParse(value.ToString(), out DateTime d)) { discoveredTypes[recordKey][PropertyType.Datetime]++; } else { discoveredTypes[recordKey][PropertyType.String]++; } break; } } } } // return object var outTypes = new Dictionary<string, PropertyType>(); // get the most frequent type of each property foreach (var typesDic in discoveredTypes) { var type = typesDic.Value.First(x => x.Value == typesDic.Value.Values.Max()).Key; outTypes.Add(typesDic.Key, type); } return outTypes; } catch (Exception e) { Logger.Error(e, e.Message); throw; } } } }
37.876289
101
0.397115
[ "MIT" ]
naveego/plugin-athena-health
PluginAthenaHealth/API/Discover/GetPropertyTypesFromRecords.cs
3,674
C#
namespace Lightweight.Scheduler.Abstractions { using System.Threading; using System.Threading.Tasks; public interface IClusterStateMonitor<TSchedulerKey> { Task MonitorClusterState(TSchedulerKey ownerSchedulerId, CancellationToken cancellationToken); } }
25.909091
102
0.77193
[ "MIT" ]
ivankaurov/ligthweight-scheduler
src/Lightweight.Scheduler.Abstractions/IClusterStateMonitor.cs
287
C#
namespace jumpfs.EnvironmentAccess { /// <summary> /// Provides a way of abstracting the file system and environment which is handy for testing /// </summary> public interface IEnvironment { ShellType ShellType { get; } bool DirectoryExists(string path); bool FileExists(string path); string ReadAllText(string path); void WriteAllText(string location, string text); public string GetEnvironmentVariable(string name); string GetFolderPath(System.Environment.SpecialFolder folderName); public string Cwd(); } }
35.411765
100
0.674419
[ "MIT" ]
gitter-badger/jumpfs
jumpfs/EnvironmentAccess/IEnvironment.cs
604
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace YammerLibrary { using System; public partial class Yammer_Compress_GetProcessingCount_Result { public Nullable<System.DateTime> StartDate { get; set; } public Nullable<System.DateTime> EndDate { get; set; } } }
34.1
85
0.532258
[ "MIT" ]
Bhaskers-Blu-Org2/YETI
YammerApplication/YammerLibrary/Yammer_Compress_GetProcessingCount_Result.cs
682
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("Akka.Interfaced.Persistence")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SaladLab")] [assembly: AssemblyProduct("Akka.Interfaced.Persistence")] [assembly: AssemblyCopyright("Copyright © 2016 SaladLab")] [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("c0d22336-c49e-4245-b39d-0b3083c28205")]
42.875
84
0.783285
[ "MIT" ]
HIPERCUBE/Akka.Interfaced
plugins/Akka.Interfaced.Persistence/Properties/AssemblyInfo.cs
1,032
C#
using MyBlog.Posts; using System.Collections.Generic; namespace MyBlog.ViewProjections.AdminPost { /// <summary> /// 所有博文视图绑定模型 /// </summary> public class AllBlogPostViewModel { /// <summary> /// 博文集合 /// </summary> public IEnumerable<Post> Posts { get; set; } /// <summary> /// 页码 /// </summary> public int PageNum { get; set; } /// <summary> /// 所有页码 /// </summary> public int AllPageNum { get; set; } /// <summary> /// 是否能下一页 /// </summary> public bool IsNext { get { return PageNum < AllPageNum; } } /// <summary> /// 能否上一页 /// </summary> public bool IsPrev { get { return PageNum > 1; } } } }
18.176471
52
0.414239
[ "Apache-2.0" ]
NobleKiss/MyBlog.NetCore
MyBlog.Core/ViewProjections/AdminPost/AllBlogPostViewModel.cs
991
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("Generator")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Generator")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("d6e72c8a-f96c-42da-9046-c50d6f3d44dc")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.388889
84
0.750371
[ "MIT" ]
secretGeek/dungeon.css
Generator/Properties/AssemblyInfo.cs
1,349
C#
using Library.Data.Entities; using System.Data.Entity.ModelConfiguration; namespace Library.Data.Mapping { public class ReviewMap : EntityTypeConfiguration<REVIEW> { public ReviewMap() { HasKey(t => t.ReviewId); ToTable("REVIEW"); Property(t => t.ReviewId).HasColumnName("ReviewId"); Property(t => t.Text).HasColumnName("Text").IsRequired().HasMaxLength(4096); } } }
23.947368
88
0.613187
[ "MIT" ]
JBeni/TSP.NET
WCF/Library.Data/Mapping/ReviewMap.cs
457
C#
using System; using NUnit.Framework; using Unity.Collections.Tests; #if !UNITY_DOTSPLAYER public class GcAllocRecorderTest { [Test] public void TestBeginEnd () { GCAllocRecorder.BeginNoGCAlloc(); GCAllocRecorder.EndNoGCAlloc(); } // NOTE: Causing GC allocation with new requires an unused variable #pragma warning disable 219 [Test] public void TestNoAlloc () { GCAllocRecorder.ValidateNoGCAllocs(() => { var p = new int(); }); } [Test] public void TestAlloc() { Assert.Throws<AssertionException>(() => { GCAllocRecorder.ValidateNoGCAllocs(() => { var p = new int[5]; }); }); } #pragma warning restore 219 } #endif namespace Unity.Collections.Tests { #if !UNITY_DOTSPLAYER public static class GCAllocRecorder { static UnityEngine.Profiling.Recorder AllocRecorder; static GCAllocRecorder() { AllocRecorder = UnityEngine.Profiling.Recorder.Get("GC.Alloc"); } public static int CountGCAllocs(Action action) { AllocRecorder.FilterToCurrentThread(); AllocRecorder.enabled = false; AllocRecorder.enabled = true; action(); AllocRecorder.enabled = false; return AllocRecorder.sampleBlockCount; } // NOTE: action is called twice to warmup any GC allocs that can happen due to static constructors etc. public static void ValidateNoGCAllocs(Action action) { // warmup CountGCAllocs(action); // actual test var count = CountGCAllocs(action); if (count != 0) throw new AssertionException($"Expected 0 GC allocations but there were {count}"); } public static void BeginNoGCAlloc() { AllocRecorder.FilterToCurrentThread(); AllocRecorder.enabled = false; AllocRecorder.enabled = true; } public static void EndNoGCAlloc() { AllocRecorder.enabled = false; int count = AllocRecorder.sampleBlockCount; if (count != 0) throw new AssertionException($"Expected 0 GC allocations but there were {count}"); } } #else public static class GCAllocRecorder { public static void ValidateNoGCAllocs(Action action) { action(); } public static void BeginNoGCAlloc() { } public static void EndNoGCAlloc() { } } #endif }
23.982301
112
0.565683
[ "MIT" ]
k77torpedo/ForgeECS
Library/PackageCache/com.unity.collections@0.1.0-preview/Unity.Collections.Tests/GcAllocRecorderTest.cs
2,710
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/winnetwk.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="DISCDLGSTRUCTA" /> struct.</summary> public static unsafe partial class DISCDLGSTRUCTATests { /// <summary>Validates that the <see cref="DISCDLGSTRUCTA" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<DISCDLGSTRUCTA>(), Is.EqualTo(sizeof(DISCDLGSTRUCTA))); } /// <summary>Validates that the <see cref="DISCDLGSTRUCTA" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(DISCDLGSTRUCTA).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="DISCDLGSTRUCTA" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(DISCDLGSTRUCTA), Is.EqualTo(40)); } else { Assert.That(sizeof(DISCDLGSTRUCTA), Is.EqualTo(20)); } } } }
35.795455
145
0.632381
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
tests/Interop/Windows/um/winnetwk/DISCDLGSTRUCTATests.cs
1,577
C#
using System; using System.Collections.Generic; using System.Text; namespace Project.Domain.Exceptions { public class ProjectDomainException : Exception { public ProjectDomainException() : base() { } public ProjectDomainException(string msg) : base(msg) { } public ProjectDomainException(string msg, Exception innerException) : base(msg, innerException) { } } }
18.12
103
0.631347
[ "Apache-2.0" ]
gyw1309631798/User.API
Project.Domain/Exceptions/ProjectDomainException.cs
455
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.Collections.Generic; using System.Runtime; using System.Runtime.Serialization; using System.Security; using System.Reflection; using System.Xml; namespace System.Runtime.Serialization.Json { internal class JsonDataContract { [SecurityCritical] private JsonDataContractCriticalHelper _helper; [SecuritySafeCritical] protected JsonDataContract(DataContract traditionalDataContract) { _helper = new JsonDataContractCriticalHelper(traditionalDataContract); } [SecuritySafeCritical] protected JsonDataContract(JsonDataContractCriticalHelper helper) { _helper = helper; } internal virtual string TypeName { get { return null; } } protected JsonDataContractCriticalHelper Helper { [SecurityCritical] get { return _helper; } } protected DataContract TraditionalDataContract { [SecuritySafeCritical] get { return _helper.TraditionalDataContract; } } private Dictionary<XmlQualifiedName, DataContract> KnownDataContracts { [SecuritySafeCritical] get { return _helper.KnownDataContracts; } } public static JsonReadWriteDelegates GetGeneratedReadWriteDelegates(DataContract c) { // this method used to be rewritten by an IL transform // with the restructuring for multi-file, this is no longer true - instead // this has become a normal method JsonReadWriteDelegates result; #if NET_NATIVE // The c passed in could be a clone which is different from the original key, // We'll need to get the original key data contract from generated assembly. DataContract keyDc = DataContract.GetDataContractFromGeneratedAssembly(c.UnderlyingType); return JsonReadWriteDelegates.GetJsonDelegates().TryGetValue(keyDc, out result) ? result : null; #else return JsonReadWriteDelegates.GetJsonDelegates().TryGetValue(c, out result) ? result : null; #endif } internal static JsonReadWriteDelegates GetReadWriteDelegatesFromGeneratedAssembly(DataContract c) { JsonReadWriteDelegates result = GetGeneratedReadWriteDelegates(c); if (result == null) { throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, c.UnderlyingType.ToString())); } else { return result; } } [SecuritySafeCritical] public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract) { return JsonDataContractCriticalHelper.GetJsonDataContract(traditionalDataContract); } public object ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { PushKnownDataContracts(context); object deserializedObject = ReadJsonValueCore(jsonReader, context); PopKnownDataContracts(context); return deserializedObject; } public virtual object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { return TraditionalDataContract.ReadXmlValue(jsonReader, context); } public void WriteJsonValue(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { PushKnownDataContracts(context); WriteJsonValueCore(jsonWriter, obj, context, declaredTypeHandle); PopKnownDataContracts(context); } public virtual void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { TraditionalDataContract.WriteXmlValue(jsonWriter, obj, context); } protected static object HandleReadValue(object obj, XmlObjectSerializerReadContext context) { context.AddNewObject(obj); return obj; } protected static bool TryReadNullAtTopLevel(XmlReaderDelegator reader) { if (reader.MoveToAttribute(JsonGlobals.typeString) && (reader.Value == JsonGlobals.nullString)) { reader.Skip(); reader.MoveToElement(); return true; } reader.MoveToElement(); return false; } protected void PopKnownDataContracts(XmlObjectSerializerContext context) { if (KnownDataContracts != null) { context.scopedKnownTypes.Pop(); } } protected void PushKnownDataContracts(XmlObjectSerializerContext context) { if (KnownDataContracts != null) { context.scopedKnownTypes.Push(KnownDataContracts); } } internal class JsonDataContractCriticalHelper { private static object s_cacheLock = new object(); private static object s_createDataContractLock = new object(); private static JsonDataContract[] s_dataContractCache = new JsonDataContract[32]; private static int s_dataContractID = 0; private static TypeHandleRef s_typeHandleRef = new TypeHandleRef(); private static Dictionary<TypeHandleRef, IntRef> s_typeToIDCache = new Dictionary<TypeHandleRef, IntRef>(new TypeHandleRefEqualityComparer()); private Dictionary<XmlQualifiedName, DataContract> _knownDataContracts; private DataContract _traditionalDataContract; private string _typeName; internal JsonDataContractCriticalHelper(DataContract traditionalDataContract) { _traditionalDataContract = traditionalDataContract; AddCollectionItemContractsToKnownDataContracts(); _typeName = string.IsNullOrEmpty(traditionalDataContract.Namespace.Value) ? traditionalDataContract.Name.Value : string.Concat(traditionalDataContract.Name.Value, JsonGlobals.NameValueSeparatorString, XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(traditionalDataContract.Namespace.Value)); } internal Dictionary<XmlQualifiedName, DataContract> KnownDataContracts { get { return _knownDataContracts; } } internal DataContract TraditionalDataContract { get { return _traditionalDataContract; } } internal virtual string TypeName { get { return _typeName; } } public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract) { int id = JsonDataContractCriticalHelper.GetId(traditionalDataContract.UnderlyingType.TypeHandle); JsonDataContract dataContract = s_dataContractCache[id]; if (dataContract == null) { dataContract = CreateJsonDataContract(id, traditionalDataContract); s_dataContractCache[id] = dataContract; } return dataContract; } internal static int GetId(RuntimeTypeHandle typeHandle) { lock (s_cacheLock) { IntRef id; s_typeHandleRef.Value = typeHandle; if (!s_typeToIDCache.TryGetValue(s_typeHandleRef, out id)) { int value = s_dataContractID++; if (value >= s_dataContractCache.Length) { int newSize = (value < Int32.MaxValue / 2) ? value * 2 : Int32.MaxValue; if (newSize <= value) { Fx.Assert("DataContract cache overflow"); throw new SerializationException(SR.DataContractCacheOverflow); } Array.Resize<JsonDataContract>(ref s_dataContractCache, newSize); } id = new IntRef(value); try { s_typeToIDCache.Add(new TypeHandleRef(typeHandle), id); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } } return id.Value; } } private static JsonDataContract CreateJsonDataContract(int id, DataContract traditionalDataContract) { lock (s_createDataContractLock) { JsonDataContract dataContract = s_dataContractCache[id]; if (dataContract == null) { Type traditionalDataContractType = traditionalDataContract.GetType(); if (traditionalDataContractType == typeof(ObjectDataContract)) { dataContract = new JsonObjectDataContract(traditionalDataContract); } else if (traditionalDataContractType == typeof(StringDataContract)) { dataContract = new JsonStringDataContract((StringDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(UriDataContract)) { dataContract = new JsonUriDataContract((UriDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(QNameDataContract)) { dataContract = new JsonQNameDataContract((QNameDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(ByteArrayDataContract)) { dataContract = new JsonByteArrayDataContract((ByteArrayDataContract)traditionalDataContract); } else if (traditionalDataContract.IsPrimitive || traditionalDataContract.UnderlyingType == Globals.TypeOfXmlQualifiedName) { dataContract = new JsonDataContract(traditionalDataContract); } else if (traditionalDataContractType == typeof(ClassDataContract)) { dataContract = new JsonClassDataContract((ClassDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(EnumDataContract)) { dataContract = new JsonEnumDataContract((EnumDataContract)traditionalDataContract); } else if ((traditionalDataContractType == typeof(GenericParameterDataContract)) || (traditionalDataContractType == typeof(SpecialTypeDataContract))) { dataContract = new JsonDataContract(traditionalDataContract); } else if (traditionalDataContractType == typeof(CollectionDataContract)) { dataContract = new JsonCollectionDataContract((CollectionDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(XmlDataContract)) { dataContract = new JsonXmlDataContract((XmlDataContract)traditionalDataContract); } else { throw new ArgumentException(SR.Format(SR.JsonTypeNotSupportedByDataContractJsonSerializer, traditionalDataContract.UnderlyingType), "traditionalDataContract"); } } return dataContract; } } private void AddCollectionItemContractsToKnownDataContracts() { if (_traditionalDataContract.KnownDataContracts != null) { foreach (KeyValuePair<XmlQualifiedName, DataContract> knownDataContract in _traditionalDataContract.KnownDataContracts) { if (!object.ReferenceEquals(knownDataContract, null)) { CollectionDataContract collectionDataContract = knownDataContract.Value as CollectionDataContract; while (collectionDataContract != null) { DataContract itemContract = collectionDataContract.ItemContract; if (_knownDataContracts == null) { _knownDataContracts = new Dictionary<XmlQualifiedName, DataContract>(); } if (!_knownDataContracts.ContainsKey(itemContract.StableName)) { _knownDataContracts.Add(itemContract.StableName, itemContract); } if (collectionDataContract.ItemType.GetTypeInfo().IsGenericType && collectionDataContract.ItemType.GetGenericTypeDefinition() == typeof(KeyValue<,>)) { DataContract itemDataContract = DataContract.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionDataContract.ItemType.GetTypeInfo().GenericTypeArguments)); if (!_knownDataContracts.ContainsKey(itemDataContract.StableName)) { _knownDataContracts.Add(itemDataContract.StableName, itemDataContract); } } if (!(itemContract is CollectionDataContract)) { break; } collectionDataContract = itemContract as CollectionDataContract; } } } } } } } #if NET_NATIVE public class JsonReadWriteDelegates #else internal class JsonReadWriteDelegates #endif { // this is the global dictionary for JSON delegates introduced for multi-file private static Dictionary<DataContract, JsonReadWriteDelegates> s_jsonDelegates = new Dictionary<DataContract, JsonReadWriteDelegates>(); public static Dictionary<DataContract, JsonReadWriteDelegates> GetJsonDelegates() { return s_jsonDelegates; } public JsonFormatClassWriterDelegate ClassWriterDelegate { get; set; } public JsonFormatClassReaderDelegate ClassReaderDelegate { get; set; } public JsonFormatCollectionWriterDelegate CollectionWriterDelegate { get; set; } public JsonFormatCollectionReaderDelegate CollectionReaderDelegate { get; set; } public JsonFormatGetOnlyCollectionReaderDelegate GetOnlyCollectionReaderDelegate { get; set; } } }
45.257534
339
0.56995
[ "MIT" ]
mellinoe/corefx
src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.cs
16,519
C#
#region License // Copyright (c) 2011, ClearCanvas Inc. // All rights reserved. // http://www.clearcanvas.ca // // This software is licensed under the Open Software License v3.0. // For the complete license, see http://www.clearcanvas.ca/OSLv3.0 #endregion using System; using System.ComponentModel; using System.Windows.Forms; namespace ClearCanvas.Desktop.View.WinForms { public partial class TextAreaField : UserControl { public TextAreaField() { InitializeComponent(); } public string Value { get { return NullIfEmpty(_textBox.Text); } set { _textBox.Text = value; } } public event EventHandler ValueChanged { add { _textBox.TextChanged += value; } remove { _textBox.TextChanged -= value; } } [Localizable(true)] public string LabelText { get { return _label.Text; } set { _label.Text = value; } } [DefaultValue(false)] public bool ReadOnly { get { return _textBox.ReadOnly; } set { _textBox.ReadOnly = value; } } [DefaultValue(true)] public bool WordWrap { get { return _textBox.WordWrap; } set { _textBox.WordWrap = value; } } [DefaultValue(ScrollBars.None)] public ScrollBars ScrollBars { get { return _textBox.ScrollBars; } set { _textBox.ScrollBars = value; } } [DefaultValue(32767)] public int MaximumLength { get { return _textBox.MaxLength; } set { _textBox.MaxLength = value; } } private static string NullIfEmpty(string value) { return (value != null && value.Length == 0) ? null : value; } private void _textBox_DragEnter(object sender, DragEventArgs e) { if (_textBox.ReadOnly) { e.Effect = DragDropEffects.None; return; } if (e.Data.GetDataPresent(DataFormats.Text)) { e.Effect = DragDropEffects.Copy; } else { e.Effect = DragDropEffects.None; } } private void _textBox_DragDrop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.Text)) { string dropString = (String)e.Data.GetData(typeof(String)); // Insert string at the current keyboard cursor int currentIndex = _textBox.SelectionStart; _textBox.Text = string.Concat( _textBox.Text.Substring(0, currentIndex), dropString, _textBox.Text.Substring(currentIndex)); } } } }
24.223214
72
0.570955
[ "Apache-2.0" ]
SNBnani/Xian
Desktop/View/WinForms/TextAreaField.cs
2,713
C#
namespace advisor.Features { using System.IO; using System.Threading; using System.Threading.Tasks; using advisor.Model; using advisor.Persistence; using MediatR; using Microsoft.EntityFrameworkCore; public record ImportMap(long PlayerId, string Source) : IRequest; public class ImportMapHandler : IRequestHandler<ImportMap> { public ImportMapHandler(Database db, IMediator mediator) { this.db = db; this.mediator = mediator; } private readonly Database db; private readonly IMediator mediator; public async Task<MediatR.Unit> Handle(ImportMap request, CancellationToken cancellationToken) { DbPlayer player = await db.Players .Include(x => x.Game) .SingleOrDefaultAsync(x => x.Id == request.PlayerId); if (player == null) return Unit.Value; using var textReader = new StringReader(request.Source); using var atlantisReader = new AtlantisReportJsonConverter(textReader, new RegionsSection() ); var json = await atlantisReader.ReadAsJsonAsync(); var report = json.ToObject<JReport>(); int earliestTurn = player.LastTurnNumber; await mediator.Send(new ParseReports(player.Id, earliestTurn, report)); return Unit.Value; } } }
32.860465
104
0.634112
[ "MIT" ]
gelzis/atlantis-economy-adivsor
server/Features/ImportMap.cs
1,413
C#
using UnityEngine; namespace ST.Play { public class ShipMarker : MonoBehaviour { #region Editor customization #pragma warning disable 0649 public bool ownedByClient; public ShipView shipView; [SerializeField] private GameObject forLocalPlayer; [SerializeField] private GameObject forDistantPlayer; [SerializeField] private MeshRenderer forDistantPlayerMesh; #pragma warning restore 0649 #endregion #region Public variables #endregion #region Unity callbacks private void Start() { forLocalPlayer.SetActive(ownedByClient); forDistantPlayer.SetActive(!ownedByClient); } #endregion } }
21.594595
55
0.60826
[ "Unlicense" ]
ganlhi/saganami-tactics
Saganami Tactics/Assets/ST/Play/ShipMarker.cs
801
C#
using System; using System.Collections.Generic; using System.IO; using JetBrains.Annotations; using UnityEditor; using UnityEditor.Build; using UnityEditor.Build.Reporting; using UnityEditor.Callbacks; #if UNITY_IOS using UnityEditor.iOS.Xcode; #endif using UnityEngine; // Starting with Unity 2019.3, plugins are built into UnityFramework.framework // and frameworks cant have a bridging header. #if !UNITY_2019_3_OR_NEWER namespace Commons.Editor { /// <summary> /// Combines the 'Bridging-Header.h' files into one file. /// </summary> /// <remarks> /// Build fails when two plugin files are named the same: /// 105 [10:06:16 AM] Plugin 'Bridging-Header.h' is used from several locations: /// 106 [10:06:16 AM] Packages/com.gamingforgood.golive/Runtime/Plugins/iOS/Bridging-Header.h would be copied to <PluginPath>/Bridging-Header.h /// 107 [10:06:16 AM] Assets/Plugins/iOS/Bridging-Header.h would be copied to <PluginPath>/Bridging-Header.h /// 108 [10:06:16 AM] Please fix plugin settings and try again. /// </remarks> internal class PreprocessBrigingHeader : IPreprocessBuildWithReport { public void OnPreprocessBuild(BuildReport report) { if (report.summary.platform != BuildTarget.iOS) return; CombinedContents = CombineObjcBridgingHeaders(); } /// <summary> /// Because unity reloads assemblies between pre and post build, the values of /// static fields cannot be trusted to store data. /// </summary> private static string ContentsCacheFilepath => Path.Combine(Application.temporaryCachePath, "CombinedContents.h"); public static string CombinedContents { get => File.Exists(ContentsCacheFilepath) ? File.ReadAllText(ContentsCacheFilepath) : null; private set => File.WriteAllText(ContentsCacheFilepath, value); } [PostProcessBuild(99999)] private static void AddToXcodeProject(BuildTarget target, string pathToBuildProject) { if (target != BuildTarget.iOS) return; try { // postbuild cleanup RespawnDeletedFiles(); // save the generated bridging header to file var generatedOutputPath = Path.Combine(pathToBuildProject, BridgingHeaderPathInXcodeproj); Directory.CreateDirectory(Path.GetDirectoryName(generatedOutputPath)); File.WriteAllText(generatedOutputPath, CombinedContents); Debug.Log( $"wrote generated bridging header to {generatedOutputPath}"); // add the generated file to xcode project #if UNITY_IOS var pbx = new PBXProject(); pbx.ReadFromFile(PBXProject.GetPBXProjectPath(pathToBuildProject)); if (!pbx.ContainsFileByProjectPath(BridgingHeaderPathInXcodeproj)) { var targetGuid = pbx.GetUnityMainTargetGuid(); pbx.AddFileToBuild(targetGuid, pbx.AddFile(BridgingHeaderPathInXcodeproj, BridgingHeaderPathInXcodeproj)); } #endif } catch (Exception ex) { throw new BuildFailedException(ex); } } /// Combines the contents of all bridging header files and deletes /// the original files. /// <returns>Combined contents of all bridging header files</returns> [CanBeNull] private static string CombineObjcBridgingHeaders() { bridgingHeaders = new Dictionary<string, string>(); var bridgingHeaderFiles = FileFinder.FindAssetsNamed(BridgingHeaderFilename); Debug.Log($"found {bridgingHeaderFiles.Length} bridging header files"); if (bridgingHeaderFiles.Length == 0) return null; HashSet<string> uniqueLines = new HashSet<string>(); foreach (var filepath in bridgingHeaderFiles) { var lines = File.ReadAllLines(filepath); Debug.Log($"adding {filepath}"); uniqueLines.Add($"\n/// {filepath}"); foreach (var line in lines) { var trimmed = line.Trim(); if (!String.IsNullOrEmpty(trimmed)) { uniqueLines.Add(trimmed); } } bridgingHeaders.Add(filepath, File.ReadAllText(filepath)); bridgingHeaders.Add(filepath + ".meta", File.ReadAllText(filepath + ".meta")); AssetDatabase.DeleteAsset(filepath); } return String.Join("\n", uniqueLines); } #region recreate the original bridging header files private static void RespawnDeletedFiles() { if (bridgingHeaders == null) return; foreach (var pair in bridgingHeaders) { var filepath = pair.Key; var contents = pair.Value; Debug.Log($"respawning {contents.Length} chars to: " + filepath); File.WriteAllText(filepath, contents); } bridgingHeaders.Clear(); } /// <summary> /// Filepath -> file contents /// </summary> private static Dictionary<string, string> bridgingHeaders; #endregion /// package consumers (e.g. IdleGame) should name their swift->objc briding header like this public const string BridgingHeaderFilename = "Bridging-Header.h"; /// <summary> /// Relative path to the output bridging header file inside the generated xcode project. /// </summary> public const string BridgingHeaderPathInXcodeproj = BridgingHeaderFilename; /// Doesnt really matter public int callbackOrder => 10; [MenuItem("Build/Advanced/Test create Bridging-Header.h")] private static void MenuTest() { var contents = CombineObjcBridgingHeaders(); var dummyFile = Path.Combine(Application.dataPath, "..", $"test_create_{BridgingHeaderFilename}"); File.WriteAllText(dummyFile, contents); RespawnDeletedFiles(); } } } #endif
39.949045
148
0.618463
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
singularity-group/mobile-build-scripts
Packages/com.gamingforgood.mobile_build_scripts/Editor/PreprocessBridgingHeader.cs
6,272
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; using Flow.Launcher.Core; using Flow.Launcher.Core.Configuration; using Flow.Launcher.Core.ExternalPlugins; using Flow.Launcher.Core.Plugin; using Flow.Launcher.Core.Resource; using Flow.Launcher.Helper; using Flow.Launcher.Infrastructure; using Flow.Launcher.Infrastructure.Image; using Flow.Launcher.Infrastructure.Storage; using Flow.Launcher.Infrastructure.UserSettings; using Flow.Launcher.Plugin; using Flow.Launcher.Plugin.SharedModels; namespace Flow.Launcher.ViewModel { public class SettingWindowViewModel : BaseModel { private readonly Updater _updater; private readonly IPortable _portable; private readonly FlowLauncherJsonStorage<Settings> _storage; public SettingWindowViewModel(Updater updater, IPortable portable) { _updater = updater; _portable = portable; _storage = new FlowLauncherJsonStorage<Settings>(); Settings = _storage.Load(); Settings.PropertyChanged += (s, e) => { switch (e.PropertyName) { case nameof(Settings.ActivateTimes): OnPropertyChanged(nameof(ActivatedTimes)); break; } }; } public Settings Settings { get; set; } public async void UpdateApp() { await _updater.UpdateAppAsync(App.API, false); } public bool AutoUpdates { get => Settings.AutoUpdates; set { Settings.AutoUpdates = value; if (value) UpdateApp(); } } // This is only required to set at startup. When portable mode enabled/disabled a restart is always required private bool _portableMode = DataLocation.PortableDataLocationInUse(); public bool PortableMode { get => _portableMode; set { if (!_portable.CanUpdatePortability()) return; if (DataLocation.PortableDataLocationInUse()) { _portable.DisablePortableMode(); } else { _portable.EnablePortableMode(); } } } public void Save() { foreach (var vm in PluginViewModels) { var id = vm.PluginPair.Metadata.ID; Settings.PluginSettings.Plugins[id].Disabled = vm.PluginPair.Metadata.Disabled; Settings.PluginSettings.Plugins[id].Priority = vm.Priority; } PluginManager.Save(); _storage.Save(); } #region general // todo a better name? public class LastQueryMode { public string Display { get; set; } public Infrastructure.UserSettings.LastQueryMode Value { get; set; } } public List<LastQueryMode> LastQueryModes { get { List<LastQueryMode> modes = new List<LastQueryMode>(); var enums = (Infrastructure.UserSettings.LastQueryMode[])Enum.GetValues(typeof(Infrastructure.UserSettings.LastQueryMode)); foreach (var e in enums) { var key = $"LastQuery{e}"; var display = _translater.GetTranslation(key); var m = new LastQueryMode { Display = display, Value = e, }; modes.Add(m); } return modes; } } public string Language { get { return Settings.Language; } set { InternationalizationManager.Instance.ChangeLanguage(value); if (InternationalizationManager.Instance.PromptShouldUsePinyin(value)) ShouldUsePinyin = true; } } public bool ShouldUsePinyin { get { return Settings.ShouldUsePinyin; } set { Settings.ShouldUsePinyin = value; } } public List<string> QuerySearchPrecisionStrings { get { var precisionStrings = new List<string>(); var enumList = Enum.GetValues(typeof(SearchPrecisionScore)).Cast<SearchPrecisionScore>().ToList(); enumList.ForEach(x => precisionStrings.Add(x.ToString())); return precisionStrings; } } public List<string> OpenResultModifiersList => new List<string> { KeyConstant.Alt, KeyConstant.Ctrl, $"{KeyConstant.Ctrl}+{KeyConstant.Alt}" }; private Internationalization _translater => InternationalizationManager.Instance; public List<Language> Languages => _translater.LoadAvailableLanguages(); public IEnumerable<int> MaxResultsRange => Enumerable.Range(2, 16); public string TestProxy() { var proxyServer = Settings.Proxy.Server; var proxyUserName = Settings.Proxy.UserName; if (string.IsNullOrEmpty(proxyServer)) { return InternationalizationManager.Instance.GetTranslation("serverCantBeEmpty"); } if (Settings.Proxy.Port <= 0) { return InternationalizationManager.Instance.GetTranslation("portCantBeEmpty"); } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_updater.GitHubRepository); if (string.IsNullOrEmpty(proxyUserName) || string.IsNullOrEmpty(Settings.Proxy.Password)) { request.Proxy = new WebProxy(proxyServer, Settings.Proxy.Port); } else { request.Proxy = new WebProxy(proxyServer, Settings.Proxy.Port) { Credentials = new NetworkCredential(proxyUserName, Settings.Proxy.Password) }; } try { var response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { return InternationalizationManager.Instance.GetTranslation("proxyIsCorrect"); } else { return InternationalizationManager.Instance.GetTranslation("proxyConnectFailed"); } } catch { return InternationalizationManager.Instance.GetTranslation("proxyConnectFailed"); } } #endregion #region plugin public static string Plugin => @"https://github.com/Flow-Launcher/Flow.Launcher.PluginsManifest"; public PluginViewModel SelectedPlugin { get; set; } public IList<PluginViewModel> PluginViewModels { get { var metadatas = PluginManager.AllPlugins .OrderBy(x => x.Metadata.Disabled) .ThenBy(y => y.Metadata.Name) .Select(p => new PluginViewModel { PluginPair = p }) .ToList(); return metadatas; } } public IList<UserPlugin> ExternalPlugins { get { return PluginsManifest.UserPlugins; } } public Control SettingProvider { get { var settingProvider = SelectedPlugin.PluginPair.Plugin as ISettingProvider; if (settingProvider != null) { var control = settingProvider.CreateSettingPanel(); control.HorizontalAlignment = HorizontalAlignment.Stretch; control.VerticalAlignment = VerticalAlignment.Stretch; return control; } else { return new Control(); } } } public async Task RefreshExternalPluginsAsync() { await PluginsManifest.UpdateManifestAsync(); OnPropertyChanged(nameof(ExternalPlugins)); } #endregion #region theme public static string Theme => @"https://flow-launcher.github.io/docs/#/how-to-create-a-theme"; public string SelectedTheme { get { return Settings.Theme; } set { Settings.Theme = value; ThemeManager.Instance.ChangeTheme(value); if (ThemeManager.Instance.BlurEnabled && Settings.UseDropShadowEffect) DropShadowEffect = false; } } public List<string> Themes => ThemeManager.Instance.LoadAvailableThemes().Select(Path.GetFileNameWithoutExtension).ToList(); public bool DropShadowEffect { get { return Settings.UseDropShadowEffect; } set { if (ThemeManager.Instance.BlurEnabled && value) { MessageBox.Show(InternationalizationManager.Instance.GetTranslation("shadowEffectNotAllowed")); return; } if (value) { ThemeManager.Instance.AddDropShadowEffectToCurrentTheme(); } else { ThemeManager.Instance.RemoveDropShadowEffectFromCurrentTheme(); } Settings.UseDropShadowEffect = value; } } public double WindowWidthSize { get => Settings.WindowSize; set => Settings.WindowSize = value; } public bool UseGlyphIcons { get => Settings.UseGlyphIcons; set => Settings.UseGlyphIcons = value; } public Brush PreviewBackground { get { var wallpaper = WallpaperPathRetrieval.GetWallpaperPath(); if (wallpaper != null && File.Exists(wallpaper)) { var memStream = new MemoryStream(File.ReadAllBytes(wallpaper)); var bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.StreamSource = memStream; bitmap.EndInit(); var brush = new ImageBrush(bitmap) { Stretch = Stretch.UniformToFill }; return brush; } else { var wallpaperColor = WallpaperPathRetrieval.GetWallpaperColor(); var brush = new SolidColorBrush(wallpaperColor); return brush; } } } public ResultsViewModel PreviewResults { get { var results = new List<Result> { new Result { Title = "Explorer", SubTitle = "Search for files, folders and file contents", IcoPath = Path.Combine(Constant.ProgramDirectory, @"Plugins\Flow.Launcher.Plugin.Explorer\Images\explorer.png") }, new Result { Title = "WebSearch", SubTitle = "Search the web with different search engine support", IcoPath =Path.Combine(Constant.ProgramDirectory, @"Plugins\Flow.Launcher.Plugin.WebSearch\Images\web_search.png") }, new Result { Title = "Program", SubTitle = "Launch programs as admin or a different user", IcoPath =Path.Combine(Constant.ProgramDirectory, @"Plugins\Flow.Launcher.Plugin.Program\Images\program.png") }, new Result { Title = "ProcessKiller", SubTitle = "Terminate unwanted processes", IcoPath =Path.Combine(Constant.ProgramDirectory, @"Plugins\Flow.Launcher.Plugin.ProcessKiller\Images\app.png") } }; var vm = new ResultsViewModel(Settings); vm.AddResults(results, "PREVIEW"); return vm; } } public FontFamily SelectedQueryBoxFont { get { if (Fonts.SystemFontFamilies.Count(o => o.FamilyNames.Values != null && o.FamilyNames.Values.Contains(Settings.QueryBoxFont)) > 0) { var font = new FontFamily(Settings.QueryBoxFont); return font; } else { var font = new FontFamily("Segoe UI"); return font; } } set { Settings.QueryBoxFont = value.ToString(); ThemeManager.Instance.ChangeTheme(Settings.Theme); } } public FamilyTypeface SelectedQueryBoxFontFaces { get { var typeface = SyntaxSugars.CallOrRescueDefault( () => SelectedQueryBoxFont.ConvertFromInvariantStringsOrNormal( Settings.QueryBoxFontStyle, Settings.QueryBoxFontWeight, Settings.QueryBoxFontStretch )); return typeface; } set { Settings.QueryBoxFontStretch = value.Stretch.ToString(); Settings.QueryBoxFontWeight = value.Weight.ToString(); Settings.QueryBoxFontStyle = value.Style.ToString(); ThemeManager.Instance.ChangeTheme(Settings.Theme); } } public FontFamily SelectedResultFont { get { if (Fonts.SystemFontFamilies.Count(o => o.FamilyNames.Values != null && o.FamilyNames.Values.Contains(Settings.ResultFont)) > 0) { var font = new FontFamily(Settings.ResultFont); return font; } else { var font = new FontFamily("Segoe UI"); return font; } } set { Settings.ResultFont = value.ToString(); ThemeManager.Instance.ChangeTheme(Settings.Theme); } } public FamilyTypeface SelectedResultFontFaces { get { var typeface = SyntaxSugars.CallOrRescueDefault( () => SelectedResultFont.ConvertFromInvariantStringsOrNormal( Settings.ResultFontStyle, Settings.ResultFontWeight, Settings.ResultFontStretch )); return typeface; } set { Settings.ResultFontStretch = value.Stretch.ToString(); Settings.ResultFontWeight = value.Weight.ToString(); Settings.ResultFontStyle = value.Style.ToString(); ThemeManager.Instance.ChangeTheme(Settings.Theme); } } public string ThemeImage => Constant.QueryTextBoxIconImagePath; #endregion #region hotkey public CustomPluginHotkey SelectedCustomPluginHotkey { get; set; } #endregion #region about public string Website => Constant.Website; public string ReleaseNotes => _updater.GitHubRepository + @"/releases/latest"; public string Documentation => Constant.Documentation; public static string Version => Constant.Version; public string ActivatedTimes => string.Format(_translater.GetTranslation("about_activate_times"), Settings.ActivateTimes); #endregion } }
33.410359
151
0.516277
[ "MIT" ]
XavBryant/Flow.Launcher
Flow.Launcher/ViewModel/SettingWindowViewModel.cs
16,772
C#
namespace P04_InfernoInfinity.Core { using System; using System.Collections.Generic; using Contracts; public class Inventory : IInventory { private Dictionary<string, IWeapon> weaponStorage; public IReadOnlyDictionary<string, IWeapon> Weapons => weaponStorage; public Inventory() { weaponStorage = new Dictionary<string, IWeapon>(); } public void AddGemToSocket(string weaponName, int gemSlot, IGem gem) { IWeapon weapon = weaponStorage[weaponName]; weapon.AddGem(gemSlot, gem); } public void AddWeapon(IWeapon weapon) { weaponStorage.Add(weapon.Name, weapon); } public void PrintWeapon(string weaponName) { IWeapon weapon = weaponStorage[weaponName]; Console.WriteLine(weapon); } public void RemoveGemFromSocket(string weaponName, int gemSlot, IGem gem) { IWeapon weapon = weaponStorage[weaponName]; weapon.RemoveGem(gemSlot, gem); } } }
25.674419
81
0.605072
[ "MIT" ]
teodortenchev/C-Sharp-Advanced-Coursework
C# OOP Advanced/Reflection-Exercises/P04_InfernoInfinity/Core/Inventory.cs
1,106
C#
namespace TeisterMask.Data { using Microsoft.EntityFrameworkCore; using TeisterMask.Data.Models; public class TeisterMaskContext : DbContext { public TeisterMaskContext() { } public TeisterMaskContext(DbContextOptions options) : base(options) { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder .UseSqlServer(Configuration.ConnectionString); } } public DbSet<Employee> Employees { get; set; } public DbSet<EmployeeTask> EmployeesTasks { get; set; } public DbSet<Project> Projects { get; set; } public DbSet<Task> Tasks { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<EmployeeTask>(entity => { entity.HasKey(e => new { e.EmployeeId, e.TaskId }); }); } } }
30
85
0.592381
[ "MIT" ]
martinsivanov/CSharp-Databases-January-2021
01 - Entity FrameworkCore/Exams Exercise/C# DB Advanced Exam - 04 April 2021/TeisterMask/Data/TeisterMaskContext.cs
1,052
C#
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using NuGet.Configuration; using NuGet.ProjectModel; using NuGet.Test.Utility; using Xunit; namespace NuGet.Commands.Test { public class MinClientVersionTests { [Fact] public async Task MinClientVersion_DependencyVersionTooHigh() { // Arrange var sources = new List<PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.3"": { ""dependencies"": { ""packageA"": ""1.0.0"" } } } }"; using (var workingDir = TestFileSystemUtility.CreateRandomTestFolder()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var logger = new TestLogger(); var request = new RestoreRequest(spec1, sources, packagesDir.FullName, logger); request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json"); var packageBContext = new SimpleTestPackageContext() { Id = "packageB", Version = "1.0.0", MinClientVersion = "9.0.0" }; var packageAContext = new SimpleTestPackageContext() { Id = "packageA", Version = "1.0.0", MinClientVersion = "1.0.0", Dependencies = new List<SimpleTestPackageContext>() { packageBContext } }; SimpleTestPackageUtility.CreatePackages(packageSource.FullName, packageAContext, packageBContext); Exception ex = null; // Act var command = new RestoreCommand(request); try { var result = await command.ExecuteAsync(); } catch (Exception exception) { ex = exception; } // Assert Assert.Contains("The 'packageB 1.0.0' package requires NuGet client version '9.0.0' or above, but the current NuGet version is", ex.Message); } } } }
34.93617
157
0.507308
[ "Apache-2.0" ]
MarkOsborneMS/NuGet.Client
test/NuGet.Core.Tests/NuGet.Commands.Test/MinClientVersionTests.cs
3,286
C#
using System; using System.Linq; using System.Text.RegularExpressions; using JetBrains.Annotations; using WireMock.Validation; namespace WireMock.Matchers { /// <summary> /// Regular Expression Matcher /// </summary> /// <inheritdoc cref="IStringMatcher"/> /// <inheritdoc cref="IIgnoreCaseMatcher"/> public class RegexMatcher : IStringMatcher, IIgnoreCaseMatcher { private readonly string[] _patterns; private readonly Regex[] _expressions; /// <inheritdoc cref="IMatcher.MatchBehaviour"/> public MatchBehaviour MatchBehaviour { get; } /// <summary> /// Initializes a new instance of the <see cref="RegexMatcher"/> class. /// </summary> /// <param name="pattern">The pattern.</param> /// <param name="ignoreCase">Ignore the case from the pattern.</param> public RegexMatcher([NotNull, RegexPattern] string pattern, bool ignoreCase = false) : this(new[] { pattern }, ignoreCase) { } /// <summary> /// Initializes a new instance of the <see cref="RegexMatcher"/> class. /// </summary> /// <param name="matchBehaviour">The match behaviour.</param> /// <param name="pattern">The pattern.</param> /// <param name="ignoreCase">Ignore the case from the pattern.</param> public RegexMatcher(MatchBehaviour matchBehaviour, [NotNull, RegexPattern] string pattern, bool ignoreCase = false) : this(matchBehaviour, new[] { pattern }, ignoreCase) { } /// <summary> /// Initializes a new instance of the <see cref="RegexMatcher"/> class. /// </summary> /// <param name="patterns">The patterns.</param> /// <param name="ignoreCase">Ignore the case from the pattern.</param> public RegexMatcher([NotNull, RegexPattern] string[] patterns, bool ignoreCase = false) : this(MatchBehaviour.AcceptOnMatch, patterns, ignoreCase) { } /// <summary> /// Initializes a new instance of the <see cref="RegexMatcher"/> class. /// </summary> /// <param name="matchBehaviour">The match behaviour.</param> /// <param name="patterns">The patterns.</param> /// <param name="ignoreCase">Ignore the case from the pattern.</param> public RegexMatcher(MatchBehaviour matchBehaviour, [NotNull, RegexPattern] string[] patterns, bool ignoreCase = false) { Check.NotNull(patterns, nameof(patterns)); _patterns = patterns; IgnoreCase = ignoreCase; MatchBehaviour = matchBehaviour; RegexOptions options = RegexOptions.Compiled; if (ignoreCase) { options |= RegexOptions.IgnoreCase; } _expressions = patterns.Select(p => new Regex(p, options)).ToArray(); } /// <inheritdoc cref="IStringMatcher.IsMatch"/> public double IsMatch(string input) { double match = MatchScores.Mismatch; if (input != null) { try { match = MatchScores.ToScore(_expressions.Select(e => e.IsMatch(input))); } catch (Exception) { // just ignore exception } } return MatchBehaviourHelper.Convert(MatchBehaviour, match); } /// <inheritdoc cref="IStringMatcher.GetPatterns"/> public virtual string[] GetPatterns() { return _patterns; } /// <inheritdoc cref="IMatcher.Name"/> public virtual string Name => "RegexMatcher"; /// <inheritdoc cref="IIgnoreCaseMatcher.IgnoreCase"/> public bool IgnoreCase { get; } } }
36.778846
177
0.585359
[ "Apache-2.0" ]
Bob11327/WireMock.Net
src/WireMock.Net/Matchers/RegexMatcher.cs
3,827
C#
using System.Threading.Tasks; using Abp.Dependency; namespace ThinkAM.ThinkEvent.Authentication.External { public abstract class ExternalAuthProviderApiBase : IExternalAuthProviderApi, ITransientDependency { public ExternalLoginProviderInfo ProviderInfo { get; set; } public void Initialize(ExternalLoginProviderInfo providerInfo) { ProviderInfo = providerInfo; } public async Task<bool> IsValidUser(string userId, string accessCode) { var userInfo = await GetUserInfo(accessCode); return userInfo.ProviderKey == userId; } public abstract Task<ExternalAuthUserInfo> GetUserInfo(string accessCode); } }
29.958333
102
0.698192
[ "MIT" ]
ThinkAM/ThinkEvent
aspnet-core/src/ThinkAM.ThinkEvent.Web.Core/Authentication/External/ExternalAuthProviderApiBase.cs
721
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Web.Models.MossViewModel { public class SendRequestViewModel { [Required] public long UserId { get; set; } [Required] public string Language { get; set; } public List<string> Files { get; set; } public Uri Response { get; set; } public string Comments { get; set; } [Required] [Range(1, 100, ErrorMessage = "Max matches range 1-100")] public int MaxMatches { get; set; } public List<string> BaseFiles { get; set; } public bool IsDirectoryMode { get; set; } public bool IsBetaRequest { get; set; } [Required] [Range(1, 1000, ErrorMessage = "The number of results to show can be in range 1-1000")] public int NumberOfResultsToShow { get; set; } } }
21.785714
95
0.604372
[ "MIT" ]
tabby336/Solution1
Solution1/Web/Models/MossViewModel/SendRequestViewModel.cs
917
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ESRI.ArcGIS.Catalog; namespace QuickFindArcCatalogAddin { public interface IFilterValue { string Filter { get; set; } } class GxFilterCustom:IGxObjectFilter,IFilterValue { public bool CanChooseObject(IGxObject @object, ref esriDoubleClickResult result) { throw new NotImplementedException(); } public bool CanDisplayObject(IGxObject @object) { //* filter is evaluated to determine if the gxobject should be displayed if (@object.Name.ToLower().Contains(this._Filter)) return true; else return false; } public bool CanSaveObject(IGxObject Location, string newObjectName, ref bool objectAlreadyExists) { throw new NotImplementedException(); } public string Description { get { return "Custom Filter"; } } public string Name { get {return "CustomFilter";} } private string _Filter; public string Filter { get { return _Filter; } set { _Filter = value != null ? value.ToLower() : ""; } } } }
23.576271
105
0.547088
[ "Apache-2.0" ]
awarrencaslys/ArcGIS-QuickFind.Net
source/QuickFindArcCatalogAddin/GxFilterCustom.cs
1,393
C#
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var userIps = new SortedDictionary<string, Dictionary<string, int>>(); while (true) { string input = Console.ReadLine(); if (input == "end") { break; } string[] tokens = input.Split(); string ip = tokens[0].Split('=')[1]; string user = tokens[2].Split('=')[1]; if (userIps.ContainsKey(user) == false) { userIps[user] = new Dictionary<string, int>(); } if (userIps[user].ContainsKey(ip) == false) { userIps[user][ip] = 0; } userIps[user][ip]++; } foreach (var item in userIps) { Console.WriteLine($"{item.Key}: "); Console.WriteLine(string.Join(", ", item.Value.Select(x => $"{x.Key} => {x.Value}")) + "."); } } }
23.795455
104
0.457498
[ "MIT" ]
MomchilSt/SoftUni
02-Programming-Fundamentals/Exercises/13. Dictionaries and Lambda - Exercises/User Logz/Program.cs
1,049
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Matrixes { class CalculatingMatrecies { static void Main() { int row = 4, col = 5; var matrix1 = new Matrix<int>(row, col); for (int r = 0; r < row; r++) { for (int c = 0; c < col; c++) { matrix1[r, c] = r + c + 2; } } row = 5; col = 3; var matrix2 = new Matrix<int>(row, col); for (int r = 0; r < row; r++) { for (int c = 0; c < col; c++) { matrix2[r, c] = r + c; } } Console.WriteLine(matrix1); Console.WriteLine(matrix2); //Console.WriteLine(matrix1 + matrix2); //Console.WriteLine(matrix1 - matrix2); Console.WriteLine(matrix1 * matrix2); if (!matrix1) { Console.WriteLine("NO"); } else { Console.WriteLine("YES"); } Type type = typeof(Matrix<int>); object[] attr = type.GetCustomAttributes(false); foreach (var item in attr) { Console.WriteLine(item); } } } }
26.611111
60
0.409186
[ "MIT" ]
zdzdz/Object-Oriented-Programming-Homeworks
02. Defining-Classes-Part-2-HW/Matrixes/CalculatingMatrecies.cs
1,439
C#
// Copyright (c) 2021 Jeevan James // This file is licensed to you under the MIT License. // See the LICENSE file in the project root for more information. using Datask.Providers.DbManagement; using Microsoft.Data.SqlClient; using Microsoft.SqlServer.Management.Common; using Microsoft.SqlServer.Management.Smo; namespace Datask.Providers.SqlServer; public sealed class SqlServerDbManagementProvider : DbManagementProvider<SqlConnection>, IDisposable { private readonly SqlConnection _serverConnection; private readonly Server _server; private readonly string _databaseName; public SqlServerDbManagementProvider(SqlConnection connection) : base(connection) { SqlConnectionStringBuilder builder = new(connection.ConnectionString); _databaseName = builder.InitialCatalog; builder.InitialCatalog = string.Empty; _serverConnection = new SqlConnection(builder.ConnectionString); _server = new Server(new ServerConnection(_serverConnection)); } public void Dispose() { _serverConnection.Dispose(); } protected override bool TryCreateDatabase() { Database database = _server.Databases[_databaseName]; if (database is not null) return true; database = new Database(_server, _databaseName); database.Create(); return true; } protected override void DeleteDatabase() { Database database = _server.Databases[_databaseName]; if (database is not null) _server.KillDatabase(_databaseName); } protected override bool DatabaseExists() { return _server.Databases[_databaseName] is not null; } public override async Task ExecuteScriptsAsync(IAsyncEnumerable<string> scripts) { Database database = _server.Databases[_databaseName]; await foreach (string script in scripts) database.ExecuteNonQuery(script); } protected override void ExecuteScript(string script) { Database database = _server.Databases[_databaseName]; database.ExecuteNonQuery(script); } }
29.273973
100
0.708002
[ "MIT" ]
JeevanJames/Datask
provider/SqlServer/SqlServerDbManagementProvider.cs
2,139
C#
using System; using System.ComponentModel; using System.Diagnostics; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using AKITE.Contingent.Client.Utilities; using AKITE.Contingent.Helpers; using AKITE.Contingent.Models; namespace AKITE.Contingent.Client.Services { public class SpecialtyDataService : BaseDataService<Specialty> { private readonly HttpClient _http; public SpecialtyDataService() : base() { if (SettingsManager.GetBool("LocalMode")) { Items.Add(new Specialty { Id = 0, Name = "Абитуриенты" }); return; } _http = new HttpClient { BaseAddress = new Uri(SettingsManager.GetString("ApiBase")) }; _http.DefaultRequestHeaders.Accept.Clear(); _http.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); } public override async Task Refresh() { if (SettingsManager.GetBool("LocalMode")) { await base.Refresh(); return; } var request = await _http.GetAsync("/api/specialties"); if (!request.IsSuccessStatusCode) { Debug.WriteLine(request.StatusCode); Debug.WriteLine(await request.Content.ReadAsStringAsync()); throw new System.Exception("Не удалось получить специальности! (возможно сервер недоступен)"); } var resp = await request.Content.ReadAsAsync<BindingList<Specialty>>(); Items = resp; } } }
29.947368
110
0.591681
[ "BSD-3-Clause" ]
TrueMemer/AKITE.Contingent
Client/Services/SpecialtyDataService.cs
1,774
C#
namespace Humidifier.KinesisAnalytics { using System.Collections.Generic; using ApplicationOutputTypes; public class ApplicationOutput : Humidifier.Resource { public override string AWSTypeName { get { return @"AWS::KinesisAnalytics::ApplicationOutput"; } } /// <summary> /// ApplicationName /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalytics-applicationoutput.html#cfn-kinesisanalytics-applicationoutput-applicationname /// Required: True /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic ApplicationName { get; set; } /// <summary> /// Output /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalytics-applicationoutput.html#cfn-kinesisanalytics-applicationoutput-output /// Required: True /// UpdateType: Mutable /// Type: Output /// </summary> public Output Output { get; set; } } namespace ApplicationOutputTypes { public class KinesisFirehoseOutput { /// <summary> /// ResourceARN /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-kinesisfirehoseoutput.html#cfn-kinesisanalytics-applicationoutput-kinesisfirehoseoutput-resourcearn /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ResourceARN { get; set; } /// <summary> /// RoleARN /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-kinesisfirehoseoutput.html#cfn-kinesisanalytics-applicationoutput-kinesisfirehoseoutput-rolearn /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic RoleARN { get; set; } } public class Output { /// <summary> /// DestinationSchema /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-output.html#cfn-kinesisanalytics-applicationoutput-output-destinationschema /// Required: True /// UpdateType: Mutable /// Type: DestinationSchema /// </summary> public DestinationSchema DestinationSchema { get; set; } /// <summary> /// LambdaOutput /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-output.html#cfn-kinesisanalytics-applicationoutput-output-lambdaoutput /// Required: False /// UpdateType: Mutable /// Type: LambdaOutput /// </summary> public LambdaOutput LambdaOutput { get; set; } /// <summary> /// KinesisFirehoseOutput /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-output.html#cfn-kinesisanalytics-applicationoutput-output-kinesisfirehoseoutput /// Required: False /// UpdateType: Mutable /// Type: KinesisFirehoseOutput /// </summary> public KinesisFirehoseOutput KinesisFirehoseOutput { get; set; } /// <summary> /// KinesisStreamsOutput /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-output.html#cfn-kinesisanalytics-applicationoutput-output-kinesisstreamsoutput /// Required: False /// UpdateType: Mutable /// Type: KinesisStreamsOutput /// </summary> public KinesisStreamsOutput KinesisStreamsOutput { get; set; } /// <summary> /// Name /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-output.html#cfn-kinesisanalytics-applicationoutput-output-name /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic Name { get; set; } } public class DestinationSchema { /// <summary> /// RecordFormatType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-destinationschema.html#cfn-kinesisanalytics-applicationoutput-destinationschema-recordformattype /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic RecordFormatType { get; set; } } public class KinesisStreamsOutput { /// <summary> /// ResourceARN /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-kinesisstreamsoutput.html#cfn-kinesisanalytics-applicationoutput-kinesisstreamsoutput-resourcearn /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ResourceARN { get; set; } /// <summary> /// RoleARN /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-kinesisstreamsoutput.html#cfn-kinesisanalytics-applicationoutput-kinesisstreamsoutput-rolearn /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic RoleARN { get; set; } } public class LambdaOutput { /// <summary> /// ResourceARN /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-lambdaoutput.html#cfn-kinesisanalytics-applicationoutput-lambdaoutput-resourcearn /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ResourceARN { get; set; } /// <summary> /// RoleARN /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-lambdaoutput.html#cfn-kinesisanalytics-applicationoutput-lambdaoutput-rolearn /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic RoleARN { get; set; } } } }
35.773148
227
0.555067
[ "BSD-2-Clause" ]
jakejscott/Humidifier
src/Humidifier/KinesisAnalytics/ApplicationOutput.cs
7,727
C#
#pragma checksum "C:\Users\Administrator\source\repos\aspdotnetcoreapp\Pages\_ViewImports.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "8cedc425bb7c3e7729ec31eeb8d3b37fb5faf25d" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(aspdotnetcoreapp.Pages.Pages__ViewImports), @"mvc.1.0.view", @"/Pages/_ViewImports.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Pages/_ViewImports.cshtml", typeof(aspdotnetcoreapp.Pages.Pages__ViewImports))] namespace aspdotnetcoreapp.Pages { #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; #line 1 "C:\Users\Administrator\source\repos\aspdotnetcoreapp\Pages\_ViewImports.cshtml" using aspdotnetcoreapp; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"8cedc425bb7c3e7729ec31eeb8d3b37fb5faf25d", @"/Pages/_ViewImports.cshtml")] public class Pages__ViewImports : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { } #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
57.285714
181
0.770989
[ "Apache-2.0" ]
MyLanPangzi/.Net
aspdotnetcoreapp/obj/Debug/netcoreapp2.2/Razor/Pages/_ViewImports.g.cshtml.cs
2,406
C#
using IdentityServerPlus.Plugin.Base.Models; using System.Collections.Generic; namespace IdentityServerPlus.Plugin.Base.Interfaces { public interface IPluginProvider { string Name { get; } string Description { get; } } }
22.454545
53
0.720648
[ "Apache-2.0" ]
IdentityServerPlus/IdentityServerPlus
IdentityServerPlus.Plugin.Base/Interfaces/IPluginProvider.cs
247
C#
using ElearnerApi.Data.DataContext; using ElearnerApi.Data.Models; using ElearnerApi.Data.Models.Authentication; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Security.Claims; using System.Threading.Tasks; namespace ElearnerApi.Controllers { [Route( "[controller]/[action]" )] public class AccountController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private ApplicationDbContext _context; public AccountController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ApplicationDbContext context, ILogger<AccountController> logger) { _userManager = userManager; _signInManager = signInManager; _context = context; } [TempData] public string ErrorMessage { get; set; } [HttpGet] [AllowAnonymous] public async Task<IActionResult> Login(string returnUrl = null) { await HttpContext.SignOutAsync( IdentityConstants.ExternalScheme ); ViewData["ReturnUrl"] = returnUrl; return View( ); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var result = await _signInManager .PasswordSignInAsync( model.Email, model.Password, model.RememberMe, lockoutOnFailure: false ); if (result.Succeeded) { return RedirectToLocal( returnUrl ); } } TempData["CustomResponseAlert"] = CustomResponseAlert.GetStringResponse( ResponseStatusEnum.Danger, "Unable to log in!" ); return View( model ); } [HttpGet] [AllowAnonymous] public IActionResult Register(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View( ); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync( user, model.Password ); if (result.Succeeded) { var code = await _userManager.GenerateEmailConfirmationTokenAsync( user ); var claim = new Claim( "DefaultUserClaim", "DefaultUserAuthorization" ); var addClaimResult = await _userManager.AddClaimAsync( user, claim ); await _signInManager.SignInAsync( user, isPersistent: false ); TempData["CustomResponseAlert"] = CustomResponseAlert.GetStringResponse( ResponseStatusEnum.Success, "Thank you for registering!" ); return RedirectToLocal( returnUrl ); } AddErrors( result ); } return View( model ); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Logout() { await _signInManager.SignOutAsync( ); return RedirectToAction( nameof( HomeController.Index ), "Home" ); } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError( string.Empty, error.Description ); } } private IActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl( returnUrl )) { return Redirect( returnUrl ); } else { return RedirectToAction( nameof( HomeController.Index ), "Home" ); } } #endregion Helpers } }
31.282759
152
0.584215
[ "MIT" ]
joshuakaluba/ElearnerApi
ElearnerApi/Controllers/AccountController.cs
4,538
C#
using System; namespace AbstractFactory.Terrestres { public class Patinete : IVeiculoTerrestre { public void GetCarga() { Console.WriteLine("Motorista pegando carga!"); } public void InicieRota() { GetCarga(); Console.WriteLine("Ligando patinete e iniciando entrega!"); } } }
19.736842
71
0.565333
[ "MIT" ]
mateusOliveiraBrito/designPatterns
AbstractFactory/Terrestres/Patinete.cs
377
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnPipes : MonoBehaviour { public GameObject pipe; public float height; public float maxTime = 4f; private float timer = 0f; void Start() { GameObject newPipe = Instantiate(pipe); newPipe.transform.position = transform.position + new Vector3(0, Random.Range(-height, height),0); } void Update() { if (timer > maxTime) { GameObject newPipe = Instantiate(pipe); newPipe.transform.position = transform.position + new Vector3(0, Random.Range(-height, height),0); Destroy(newPipe, 20f); timer = 0f; } timer += Time.deltaTime; } }
23.30303
110
0.608583
[ "MIT" ]
paulohgs/flappy-bird-clone
Assets/Scripts/SpawnPipes.cs
769
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using DCL; public class AvatarAnimationEventHandler : MonoBehaviour { const string ANIM_NAME_KISS = "kiss", ANIM_NAME_MONEY = "money", ANIM_NAME_CLAP = "clap", ANIM_NAME_SNOWFLAKE = "snowfall", ANIM_NAME_HOHOHO = "hohoho"; const float MIN_EVENT_WAIT_TIME = 0.1f; AudioEvent footstepLight; AudioEvent footstepSlide; AudioEvent footstepWalk; AudioEvent footstepRun; AudioEvent clothesRustleShort; AudioEvent clap; AudioEvent throwMoney; AudioEvent blowKiss; Animation anim; float lastEventTime; StickersController stickersController; Transform footL; Transform footR; Transform handL; Transform handR; public void Init(AudioContainer audioContainer) { if (audioContainer == null) return; footstepLight = audioContainer.GetEvent("FootstepLight"); footstepSlide = audioContainer.GetEvent("FootstepSlide"); footstepWalk = audioContainer.GetEvent("FootstepWalk"); footstepRun = audioContainer.GetEvent("FootstepRun"); clothesRustleShort = audioContainer.GetEvent("ClothesRustleShort"); clap = audioContainer.GetEvent("ExpressionClap"); throwMoney = audioContainer.GetEvent("ExpressionThrowMoney"); blowKiss = audioContainer.GetEvent("ExpressionBlowKiss"); anim = GetComponent<Animation>(); stickersController = GetComponentInParent<StickersController>(); Transform[] children = GetComponentsInChildren<Transform>(); footL = AvatarBodyPartReferenceUtility.GetLeftToe(children); footR = AvatarBodyPartReferenceUtility.GetRightToe(children); handL = AvatarBodyPartReferenceUtility.GetLeftHand(children); handR = AvatarBodyPartReferenceUtility.GetRightHand(children); } public void AnimEvent_FootstepLight() { PlayAudioEvent(footstepLight); } public void AnimEvent_FootstepSlide() { PlayAudioEvent(footstepSlide); } public void AnimEvent_FootstepWalkLeft() { PlayAudioEvent(footstepWalk); } public void AnimEvent_FootstepWalkRight() { PlayAudioEvent(footstepWalk); } public void AnimEvent_FootstepRunLeft() { PlayAudioEvent(footstepRun); PlaySticker("footstep", footL.position, Vector3.up); } public void AnimEvent_FootstepRunRight() { PlayAudioEvent(footstepRun); PlaySticker("footstep", footR.position, Vector3.up); } public void AnimEvent_ClothesRustleShort() { PlayAudioEvent(clothesRustleShort); } public void AnimEvent_Clap() { if (LastEventWasTooRecent()) return; if (!AnimationWeightIsOverThreshold(0.2f, ANIM_NAME_CLAP)) return; PlayAudioEvent(clap); PlaySticker("clap", handR.position, Vector3.up); UpdateEventTime(); } public void AnimEvent_ThrowMoney() { if (LastEventWasTooRecent()) return; if (!AnimationWeightIsOverThreshold(0.2f, ANIM_NAME_MONEY)) return; PlayAudioEvent(throwMoney); PlaySticker("money", handL.position, handL.rotation.eulerAngles); UpdateEventTime(); } public void AnimEvent_BlowKiss() { if (LastEventWasTooRecent()) return; if (!AnimationWeightIsOverThreshold(0.2f, ANIM_NAME_KISS)) return; PlayAudioEvent(blowKiss); StartCoroutine(EmitHeartParticle()); UpdateEventTime(); } IEnumerator EmitHeartParticle() { yield return new WaitForSeconds(0.8f); PlaySticker("heart", handR.position, transform.rotation.eulerAngles); } public void AnimEvent_Snowflakes() { if (LastEventWasTooRecent()) return; if (!AnimationWeightIsOverThreshold(0.2f, ANIM_NAME_SNOWFLAKE)) return; PlaySticker("snowflakes", transform.position, Vector3.zero); } public void AnimEvent_Hohoho() { if (LastEventWasTooRecent()) return; if (!AnimationWeightIsOverThreshold(0.2f, ANIM_NAME_HOHOHO)) return; PlaySticker("hohoho", transform.position + transform.up * 1.5f, Vector3.zero); } void PlayAudioEvent(AudioEvent audioEvent) { if (audioEvent != null) audioEvent.Play(true); } bool AnimationWeightIsOverThreshold(float threshold, string animationName) { if (anim != null) { if (anim.isPlaying) { foreach (AnimationState state in anim) { if (state.name == animationName) { if (state.weight > threshold) return true; break; } } } } return false; } void UpdateEventTime() { lastEventTime = Time.realtimeSinceStartup; } bool LastEventWasTooRecent() { return lastEventTime + MIN_EVENT_WAIT_TIME >= Time.realtimeSinceStartup; } /// <summary> /// Plays a sticker. /// </summary> /// <param name="id">ID string of sticker</param> /// <param name="position">Position in world space</param> /// <param name="rotation">Euler angles</param> void PlaySticker(string id, Vector3 position, Vector3 direction) { if (stickersController != null) stickersController.PlaySticker(id, position, direction, false); } }
29.13089
156
0.643242
[ "Apache-2.0" ]
CarlosPolygonalMind/unity-renderer
unity-renderer/Assets/Scripts/MainScripts/DCL/Components/Avatar/AvatarAnimationEventHandler.cs
5,564
C#
/*********************************************************************** * Bachelor of Software Engineering * Media Design School * Auckland * New Zealand * * (c) 2018 Media Design School * * File Name : Note.cs * Description : A developer's note in the scene. * Project : FluxusPulse * Team Name : M Breakdown Studios * Author : Elijah Shadbolt * Mail : elijah.sha7979@mediadesign.school.nz ***********************************************************************/ using UnityEngine; public class Note : MonoBehaviour { [TextArea(3,10)] public string note; void Awake() { Destroy(this); } } //~ class
20.5
73
0.538211
[ "MIT" ]
MBreakdown/FluxusPulse
Assets/FluxusPulse/Scripts/Utilities/Note.cs
617
C#
// #if REPORT_SN // 定义 REPORT_SN 会启用报表窗的序列号 using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Xml; using System.IO; using System.Web; using System.Collections; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Ionic.Zip; using System.Data.SQLite; using DigitalPlatform; using DigitalPlatform.IO; using DigitalPlatform.Xml; using DigitalPlatform.dp2.Statis; using DigitalPlatform.Text; using DigitalPlatform.GUI; using DigitalPlatform.Range; using DigitalPlatform.CommonControl; using DigitalPlatform.Script; using DigitalPlatform.LibraryClient; using DigitalPlatform.LibraryClient.localhost; namespace dp2Circulation { /// <summary> /// 报表窗 /// </summary> public partial class ReportForm : MyForm { ReportConfigBuilder _cfg = new ReportConfigBuilder(); /// <summary> /// 构造函数 /// </summary> public ReportForm() { InitializeComponent(); } private void ReportForm_Load(object sender, EventArgs e) { if (Program.MainForm != null) { MainForm.SetControlFont(this, Program.MainForm.DefaultFont); } this.UiState = Program.MainForm.AppInfo.GetString(GetReportSection(), "ui_state", ""); /* string strError = ""; int nRet = Program.MainForm.VerifySerialCode("report", out strError); if (nRet == -1) { MessageBox.Show(Program.MainForm, "报表窗需要先设置序列号才能使用"); API.PostMessage(this.Handle, API.WM_CLOSE, 0, 0); return; } */ DelayCheck(); } delegate void Delegate_Check(); void DelayCheck() { Delegate_Check d = new Delegate_Check(Check); this.BeginInvoke(d); } void Check() { string strError = ""; int nRet = _cfg.LoadCfgFile(GetBaseDirectory(), "report_def.xml", out strError); if (nRet == -1) { this.Invoke((Action)(() => { MessageBox.Show(this, strError); })); Program.MainForm.ReportError("dp2circulation 打开 report_def.xml 文件时出现错误", "(安静报错)" + strError); // 2017/5/18 // 自动修正错误,清空配置文件 { string strFileName = Path.Combine(GetBaseDirectory(), "report_def.xml"); // 备份一下出错了的配置文件内容,便于将来追查原因 string strSavingFileName = Path.Combine(GetBaseDirectory(), "report_def.xml.error"); try { File.Copy(strFileName, strSavingFileName, true); } catch { } _cfg.InitializeCfgDom(); } } _cfg.FillList(this.listView_libraryConfig); SetStartButtonStates(); SetDailyReportButtonState(); // DelaySetUploadButtonState(); BeginUpdateUploadButtonText(); string dp2library_version = "2.60"; if (StringUtil.CompareVersion(Program.MainForm.ServerVersion, dp2library_version) < 0) { this.Invoke((Action)(() => { MessageBox.Show(this, "报表窗需要和 dp2library " + dp2library_version + " 以上版本配套使用。(当前 dp2library 版本为 " + Program.MainForm.ServerVersion + ")\r\n\r\n请及时升级 dp2library 到最新版本"); })); } else { string local_version = "0.0"; // 读入断点信息的版本号 // return: // -1 出错 // 0 文件不存在 // 1 成功 nRet = GetBreakPointVersion( out local_version, out strError); if (nRet == -1) { this.Invoke((Action)(() => { MessageBox.Show(this, strError); })); } else if (nRet == 1) { if (StringUtil.CompareVersion(local_version, _local_version) < 0) { this.Invoke((Action)(() => { MessageBox.Show(this, "由于程序升级,本地存储的结构定义发生改变,请注意稍后重新从头创建本地存储"); })); } } } } private void ReportForm_FormClosing(object sender, FormClosingEventArgs e) { } private void ReportForm_FormClosed(object sender, FormClosedEventArgs e) { StopUpdateUploadButtonText(); if (this.ErrorInfoForm != null) { try { this.ErrorInfoForm.Close(); } catch { } } if (Program.MainForm != null && Program.MainForm.AppInfo != null) Program.MainForm.AppInfo.SetString( GetReportSection(), "ui_state", this.UiState); // 删除所有输出文件 if (this.OutputFileNames != null) { Global.DeleteFiles(this.OutputFileNames); this.OutputFileNames = null; } if (_cfg != null) _cfg.Save(); } /// <summary> /// 允许或者禁止界面控件。在长操作前,一般需要禁止界面控件;操作完成后再允许 /// </summary> /// <param name="bEnable">是否允许界面控件。true 为允许, false 为禁止</param> public override void EnableControls(bool bEnable) { if (this.InvokeRequired == true) { this.Invoke(new Action<bool>(EnableControls), bEnable); return; } this.tabControl1.Enabled = bEnable; this.toolStrip_main.Enabled = bEnable; } string _connectionString = ""; // const int INSERT_BATCH = 100; // 300; // 根据日志文件创建本地 operlogxxx 表 int DoCreateOperLogTable( long lProgressStart, string strStartDate, string strEndDate, LogType logType, out string strLastDate, out long lLastIndex, out string strError) { strError = ""; strLastDate = ""; lLastIndex = 0; int nRet = 0; // strEndDate 里面可能会包含 ":0-99" 这样的附加成分 string strLeft = ""; string strEndRange = ""; StringUtil.ParseTwoPart(strEndDate, ":", out strLeft, out strEndRange); strEndDate = strLeft; string strStartRange = ""; StringUtil.ParseTwoPart(strStartDate, ":", out strLeft, out strStartRange); strStartDate = strLeft; // TODO: start 和 end 都有 range,而且 start 和 end 是同一天怎么办? // 删除不必要的索引 { this._connectionString = GetOperlogConnectionString(); // SQLiteUtil.GetConnectionString(Program.MainForm.UserDir, "operlog.bin"); // TODO: 对于 AccessLog 只删除它相关的一个索引 foreach (string type in OperLogTable.DbTypes) { nRet = OperLogTable.DeleteAdditionalIndex( type, this._connectionString, out strError); if (nRet == -1) return -1; } } List<string> filenames = null; string strWarning = ""; // 根据日期范围,发生日志文件名 // parameters: // strStartDate 起始日期。8字符 // strEndDate 结束日期。8字符 // return: // -1 错误 // 0 成功 nRet = OperLogLoader.MakeLogFileNames(strStartDate, strEndDate, true, // true, out filenames, out strWarning, out strError); if (nRet == -1) return -1; if (String.IsNullOrEmpty(strWarning) == false) { this.Invoke((Action)(() => { MessageBox.Show(this, strWarning); })); } if (filenames.Count > 0 && string.IsNullOrEmpty(strEndRange) == false) { filenames[filenames.Count - 1] = filenames[filenames.Count - 1] + ":" + strEndRange; } if (filenames.Count > 0 && string.IsNullOrEmpty(strStartRange) == false) { filenames[0] = filenames[0] + ":" + strStartRange; } this.Channel.Timeout = new TimeSpan(0, 1, 0); // 一分钟 using (SQLiteConnection connection = new SQLiteConnection(this._connectionString)) { connection.Open(); ProgressEstimate estimate = new ProgressEstimate(); OperLogLoader loader = new OperLogLoader(); loader.Channel = this.Channel; loader.Stop = this.Progress; // loader.owner = this; loader.Estimate = estimate; loader.Dates = filenames; loader.Level = 2; // Program.MainForm.OperLogLevel; loader.AutoCache = false; loader.CacheDir = ""; loader.Filter = "borrow,return,setReaderInfo,setBiblioInfo,setEntity,setOrder,setIssue,setComment,amerce,passgate,getRes"; loader.LogType = logType; loader.ProgressStart = lProgressStart; loader.Prompt -= new MessagePromptEventHandler(loader_Prompt); loader.Prompt += new MessagePromptEventHandler(loader_Prompt); // List<OperLogLine> circu_lines = new List<OperLogLine>(); MultiBuffer buffer = new MultiBuffer(); buffer.Initial(); // OperLogLineBase.MainForm = Program.MainForm; try { int nRecCount = 0; foreach (OperLogItem item in loader) { string strXml = item.Xml; if (string.IsNullOrEmpty(strXml) == true) { nRecCount++; continue; } { XmlDocument dom = new XmlDocument(); try { dom.LoadXml(strXml); } catch (Exception ex) { strError = item.Date + " 中偏移为 " + item.Index.ToString() + " 的日志记录 XML 装载到 DOM 时出错: " + ex.Message; DialogResult result = DialogResult.No; string strText = strError; this.Invoke((Action)(() => { result = MessageBox.Show(this, strText + "\r\n\r\n是否跳过此条记录继续处理?", "ReportForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); })); if (result == DialogResult.No) return -1; continue; } string strOperation = DomUtil.GetElementText(dom.DocumentElement, "operation"); string strAction = DomUtil.GetElementText(dom.DocumentElement, "action"); #if NO if (strOperation != "borrow" && strOperation != "return") { nRecCount++; continue; } #endif if (StringUtil.CompareVersion(Program.MainForm.ServerVersion, "2.74") < 0 && strOperation == "amerce" && (strAction == "amerce" || strAction == "modifyprice")) { // 重新获得当前日志记录,用最详细级别 OperLogItem new_item = loader.LoadOperLogItem(item, 0); if (new_item == null) { strError = "重新获取 OperLogItem 时出错"; return -1; } dom.LoadXml(new_item.Xml); nRet = buffer.AddLine( strOperation, dom, new_item.Date, new_item.Index, out strError); } else { nRet = buffer.AddLine( strOperation, dom, item.Date, item.Index, out strError); } if (nRet == -1) return -1; // -2 不要报错 } bool bForce = false; if (nRecCount >= 4000) bForce = true; nRet = buffer.WriteToDb(connection, true, bForce, out strError); if (bForce == true) { strLastDate = item.Date; lLastIndex = item.Index + 1; nRecCount = 0; } // 2016/5/22 if (nRet == -1) return -1; nRecCount++; } } catch (Exception ex) { strError = ExceptionUtil.GetDebugText(ex); return -1; } nRet = buffer.WriteToDb(connection, true, true, // false, out strError); if (nRet == -1) return -1; // 表示处理完成 strLastDate = ""; lLastIndex = 0; } return 0; } void loader_Prompt(object sender, MessagePromptEventArgs e) { // TODO: 不再出现此对话框。不过重试有个次数限制,同一位置失败多次后总要出现对话框才好 if (e.Actions == "yes,no,cancel") { this.Invoke((Action)(() => { DialogResult result = MessageBox.Show(this, e.MessageText + "\r\n\r\n是否重试操作?\r\n\r\n(是: 重试; 否: 跳过本次操作,继续后面的操作; 取消: 停止全部操作)", "ReportForm", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (result == DialogResult.Yes) e.ResultAction = "yes"; else if (result == DialogResult.Cancel) e.ResultAction = "cancel"; else e.ResultAction = "no"; })); } } // 根据当前命中数,调整进度条总范围 void AdjustProgressRange(long lOldCount, long lNewCount) { if (this.stop == null) return; long lDelta = lNewCount - lOldCount; if (lDelta != 0) { this.stop.SetProgressRange(this.stop.ProgressMin, this.stop.ProgressMax + lDelta); if (this._estimate != null) this._estimate.EndPosition += lDelta; } } public static string GetResultSetName() { return "#" + Guid.NewGuid().ToString(); } public void DeleteResultSet(string strResultSetName) { string strError = ""; // 删除全局结果集对象 // 管理结果集 // parameters: // strAction share/remove 分别表示共享为全局结果集对象/删除全局结果集对象 long lRet = this.Channel.ManageSearchResult( null, "remove", "", strResultSetName, out strError); if (lRet == -1) { AutoCloseMessageBox.Show( this, "删除全局结果集 '" + strResultSetName + "' 时出错" + strError, 10 * 1000, ""); } } /* 2016/5/5 下午五点过 System.Exception: 浏览事项异常: (lStart=293600 index=143) path=图书总库实体/297710;cols(1)=记录'0000297710'在库中不存在 在 dp2Circulation.ReportForm.BuildItemRecords(String strItemDbNameParam, Int64 lOldCount, Int64& lProgress, Int64& lIndex, String& strError) 位置 c:\dp2-master\dp2\dp2Circulation\Statis\ReportForm.cs:行号 514 在 dp2Circulation.ReportForm.DoPlan(XmlDocument& task_dom, String& strError) 位置 c:\dp2-master\dp2\dp2Circulation\Statis\ReportForm.cs:行号 6356 在 dp2Circulation.ReportForm.button_start_createLocalStorage_Click(Object sender, EventArgs e) 位置 c:\dp2-master\dp2\dp2Circulation\Statis\ReportForm.cs:行号 6739 在 System.Windows.Forms.Control.OnClick(EventArgs e) 在 System.Windows.Forms.Button.OnClick(EventArgs e) 在 System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) 在 System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) 在 System.Windows.Forms.Control.WndProc(Message& m) 在 System.Windows.Forms.ButtonBase.WndProc(Message& m) 在 System.Windows.Forms.Button.WndProc(Message& m) 在 System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) * */ // 复制册记录 // parameters: // lIndex [in] 起点 index // [out] 返回中断位置的 index int BuildItemRecords( string strItemDbNameParam, long lOldCount, ref long lProgress, ref long lIndex, out string strError) { strError = ""; int nRet = 0; lProgress += lIndex; using (SQLiteConnection connection = new SQLiteConnection(this._connectionString)) { connection.Open(); // 采用全局结果集 string strResultSetName = GetResultSetName(); try { this.Channel.Timeout = TimeSpan.FromMinutes(5); // 2018/5/10 long lRet = this.Channel.SearchItem(stop, strItemDbNameParam, "", // (lIndex+1).ToString() + "-", // -1, "__id", "left", // this.textBox_queryWord.Text == "" ? "left" : "exact", // 原来为left 2007/10/18 changed "zh", strResultSetName, "", // strSearchStyle "", //strOutputStyle, // (bOutputKeyCount == true ? "keycount" : ""), out strError); if (lRet == -1) return -1; if (lRet == 0) return 0; long lHitCount = lRet; AdjustProgressRange(lOldCount, lHitCount); long lStart = lIndex; long lCount = lHitCount - lIndex; DigitalPlatform.LibraryClient.localhost.Record[] searchresults = null; // bool bOutputBiblioRecPath = false; // bool bOutputItemRecPath = false; string strStyle = ""; { // bOutputBiblioRecPath = true; strStyle = "id,cols,format:@coldef:*/barcode|*/location|*/accessNo|*/parent|*/state|*/operations/operation[@name='create']/@time|*/borrower|*/borrowDate|*/borrowPeriod|*/returningDate|*/price|*/refID"; } // 实体库名 --> 书目库名 Hashtable dbname_table = new Hashtable(); List<ItemLine> lines = new List<ItemLine>(); // 装入浏览格式 for (; ; ) { if (this.InvokeRequired == false) Application.DoEvents(); // 出让界面控制权 if (stop != null && stop.State != 0) { strError = "检索共命中 " + lHitCount.ToString() + " 条,已装入 " + lStart.ToString() + " 条,用户中断..."; return -1; } lRet = this.Channel.GetSearchResult( stop, strResultSetName, lStart, lCount, strStyle, // bOutputKeyCount == true ? "keycount" : "id,cols", "zh", out searchresults, out strError); if (lRet == -1) { strError = "检索共命中 " + lHitCount.ToString() + " 条,已装入 " + lStart.ToString() + " 条," + strError; return -1; } if (lRet == 0) { return 0; } // 处理浏览结果 int i = 0; foreach (DigitalPlatform.LibraryClient.localhost.Record searchresult in searchresults) { // DigitalPlatform.LibraryClient.localhost.Record searchresult = searchresults[i]; // 2016/4/12 // 检查事项状态。主动抛出异常,避免后面出现 index 异常 if (searchresult.Cols == null) throw new Exception("浏览事项 Cols 为空: (lStart=" + lStart + " index=" + i + ") " + DumpResultItem(searchresult)); if (searchresult.Cols.Length < 12) { // throw new Exception("浏览事项异常: (lStart=" + lStart + " index=" + i + ") " + DumpResultItem(searchresult)); goto CONTINUE; // 中途遇到服务器有人删除册记录,很常见的现象 } ItemLine line = new ItemLine(); line.ItemRecPath = searchresult.Path; line.ItemBarcode = searchresult.Cols[0]; // 2016/9/26 if (string.IsNullOrEmpty(line.ItemBarcode)) line.ItemBarcode = "@refID:" + searchresult.Cols[11]; line.Location = searchresult.Cols[1]; line.AccessNo = searchresult.Cols[2]; line.State = searchresult.Cols[4]; #if NO try { line.CreateTime = DateTimeUtil.Rfc1123DateTimeStringToLocal( searchresult.Cols[5], "u"); } catch { } #endif line.CreateTime = SQLiteUtil.GetLocalTime(searchresult.Cols[5]); line.Borrower = searchresult.Cols[6]; line.BorrowTime = SQLiteUtil.GetLocalTime(searchresult.Cols[7]); line.BorrowPeriod = searchresult.Cols[8]; // line.ReturningTime = ItemLine.GetLocalTime(searchresult.Cols[9]); if (string.IsNullOrEmpty(line.BorrowTime) == false) { string strReturningTime = ""; // parameters: // strBorrowTime 借阅起点时间。u 格式 // strReturningTime 返回应还时间。 u 格式 nRet = AmerceOperLogLine.BuildReturingTimeString(line.BorrowTime, line.BorrowPeriod, out strReturningTime, out strError); if (nRet == -1) { line.ReturningTime = ""; } else line.ReturningTime = strReturningTime; } else line.ReturningTime = ""; string strPrice = searchresult.Cols[10]; long value = 0; string strUnit = ""; nRet = AmerceOperLogLine.ParsePriceString(strPrice, out value, out strUnit, out strError); if (nRet == -1) { line.Price = 0; line.Unit = ""; } else { line.Price = value; line.Unit = strUnit; } string strItemDbName = Global.GetDbName(searchresult.Path); string strBiblioDbName = (string)dbname_table[strItemDbName]; if (string.IsNullOrEmpty(strBiblioDbName) == true) { strBiblioDbName = Program.MainForm.GetBiblioDbNameFromItemDbName(strItemDbName); dbname_table[strItemDbName] = strBiblioDbName; } string strBiblioRecPath = strBiblioDbName + "/" + searchresult.Cols[3]; line.BiblioRecPath = strBiblioRecPath; lines.Add(line); CONTINUE: i++; } if (true) { // 插入一批记录 nRet = ItemLine.AppendItemLines( connection, lines, true, // 用 false 可以在测试阶段帮助发现重叠插入问题 out strError); if (nRet == -1) return -1; lIndex += lines.Count; lines.Clear(); } lStart += searchresults.Length; lCount -= searchresults.Length; lProgress += searchresults.Length; // stop.SetProgressValue(lProgress); SetProgress(lProgress); stop.SetMessage(strItemDbNameParam + " " + lStart.ToString() + "/" + lHitCount.ToString() + " " + GetProgressTimeString(lProgress)); if (lStart >= lHitCount || lCount <= 0) break; } if (lines.Count > 0) { Debug.Assert(false, ""); } } finally { this.DeleteResultSet(strResultSetName); } return 0; } } static string DumpResultItem(DigitalPlatform.LibraryClient.localhost.Record searchresult) { if (searchresult.Cols == null) return "path=" + searchresult.Path + ";cols=[null]"; return "path=" + searchresult.Path + ";cols(" + searchresult.Cols.Length.ToString() + ")=" + string.Join("|", searchresult.Cols); } // safe set progress value, between max and min void SetProgress(long lProgress) { if (lProgress <= stop.ProgressMax) stop.SetProgressValue(lProgress); else if (stop.ProgressValue < stop.ProgressMax) stop.SetProgressValue(stop.ProgressMax); } // 复制读者记录 int BuildReaderRecords( string strReaderDbNameParam, long lOldCount, ref long lProgress, ref long lIndex, out string strError) { strError = ""; int nRet = 0; lProgress += lIndex; using (SQLiteConnection connection = new SQLiteConnection(this._connectionString)) { connection.Open(); // 采用全局结果集 string strResultSetName = GetResultSetName(); try { this.Channel.Timeout = TimeSpan.FromMinutes(5); // 2018/5/10 long lRet = this.Channel.SearchReader(stop, strReaderDbNameParam, "", // (lIndex + 1).ToString() + "-", // -1, "__id", "left", // this.textBox_queryWord.Text == "" ? "left" : "exact", // 原来为left 2007/10/18 changed "zh", strResultSetName, // "", // strSearchStyle "", //strOutputStyle, // (bOutputKeyCount == true ? "keycount" : ""), out strError); if (lRet == -1) return -1; if (lRet == 0) return 0; long lHitCount = lRet; AdjustProgressRange(lOldCount, lHitCount); long lStart = lIndex; long lCount = lHitCount - lIndex; DigitalPlatform.LibraryClient.localhost.Record[] searchresults = null; string strStyle = "id,cols,format:@coldef:*/barcode|*/department|*/readerType|*/name|*/state"; // 读者库名 --> 图书馆代码 Hashtable librarycode_table = new Hashtable(); List<ReaderLine> lines = new List<ReaderLine>(); // 装入浏览格式 for (; ; ) { if (this.InvokeRequired == false) Application.DoEvents(); // 出让界面控制权 if (stop != null && stop.State != 0) { strError = "检索共命中 " + lHitCount.ToString() + " 条,已装入 " + lStart.ToString() + " 条,用户中断..."; return -1; } lRet = this.Channel.GetSearchResult( stop, strResultSetName, lStart, lCount, strStyle, // bOutputKeyCount == true ? "keycount" : "id,cols", "zh", out searchresults, out strError); if (lRet == -1) { strError = "检索共命中 " + lHitCount.ToString() + " 条,已装入 " + lStart.ToString() + " 条," + strError; return -1; } if (lRet == 0) { return 0; } // 处理浏览结果 for (int i = 0; i < searchresults.Length; i++) { DigitalPlatform.LibraryClient.localhost.Record searchresult = searchresults[i]; if (searchresult.Cols.Length < 5) { continue; // 中途遇到服务器有人删除读者记录,很常见的现象 } ReaderLine line = new ReaderLine(); line.ReaderRecPath = searchresult.Path; line.ReaderBarcode = searchresult.Cols[0]; line.Department = searchresult.Cols[1]; line.ReaderType = searchresult.Cols[2]; line.Name = searchresult.Cols[3]; line.State = searchresult.Cols[4]; string strReaderDbName = Global.GetDbName(searchresult.Path); string strLibraryCode = (string)librarycode_table[strReaderDbName]; if (string.IsNullOrEmpty(strLibraryCode) == true) { strLibraryCode = Program.MainForm.GetReaderDbLibraryCode(strReaderDbName); librarycode_table[strReaderDbName] = strLibraryCode; } line.LibraryCode = strLibraryCode; lines.Add(line); } #if NO if (lines.Count >= INSERT_BATCH || ((lStart + searchresults.Length >= lHitCount || lCount - searchresults.Length <= 0) && lines.Count > 0) ) #endif { // 插入一批读者记录 nRet = ReaderLine.AppendReaderLines( connection, lines, true, // 用 false 可以在测试阶段帮助发现重叠插入问题 out strError); if (nRet == -1) return -1; lIndex += lines.Count; lines.Clear(); } lStart += searchresults.Length; lCount -= searchresults.Length; // lIndex += searchresults.Length; lProgress += searchresults.Length; // stop.SetProgressValue(lProgress); SetProgress(lProgress); stop.SetMessage(strReaderDbNameParam + " " + lStart.ToString() + "/" + lHitCount.ToString() + " " + GetProgressTimeString(lProgress)); if (lStart >= lHitCount || lCount <= 0) break; } if (lines.Count > 0) { Debug.Assert(false, ""); } } finally { this.DeleteResultSet(strResultSetName); } return 0; } } // 复制书目记录 int BuildBiblioRecords( string strBiblioDbNameParam, long lOldCount, ref long lProgress, ref long lIndex, out string strError) { strError = ""; int nRet = 0; lProgress += lIndex; using (SQLiteConnection connection = new SQLiteConnection(this._connectionString)) { connection.Open(); string strQueryXml = ""; // 2015/11/25 // TODO: 采用全局结果集 string strResultSetName = GetResultSetName(); try { this.Channel.Timeout = new TimeSpan(0, 5, 0); long lRet = this.Channel.SearchBiblio(stop, strBiblioDbNameParam, "", // (lIndex + 1).ToString() + "-", // -1, "recid", // "__id", "left", // this.textBox_queryWord.Text == "" ? "left" : "exact", // 原来为left 2007/10/18 changed "zh", strResultSetName, "", // strSearchStyle "", //strOutputStyle, // (bOutputKeyCount == true ? "keycount" : ""), "", out strQueryXml, out strError); if (lRet == -1) return -1; if (lRet == 0) return 0; long lHitCount = lRet; AdjustProgressRange(lOldCount, lHitCount); long lStart = lIndex; long lCount = lHitCount - lIndex; DigitalPlatform.LibraryClient.localhost.Record[] searchresults = null; // string strStyle = "id,cols,format:@coldef:*/barcode|*/department|*/readerType|*/name"; string strStyle = "id"; // 读者库名 --> 图书馆代码 // Hashtable librarycode_table = new Hashtable(); List<BiblioLine> lines = new List<BiblioLine>(); List<string> biblio_recpaths = new List<string>(); // 装入浏览格式 for (; ; ) { if (this.InvokeRequired == false) Application.DoEvents(); // 出让界面控制权 if (stop != null && stop.State != 0) { strError = "检索共命中 " + lHitCount.ToString() + " 条,已装入 " + lStart.ToString() + " 条,用户中断..."; return -1; } // 2015/11/25 this.Channel.Timeout = new TimeSpan(0, 0, 30); lRet = this.Channel.GetSearchResult( stop, strResultSetName, lStart, lCount, strStyle, // bOutputKeyCount == true ? "keycount" : "id,cols", "zh", out searchresults, out strError); if (lRet == -1) { strError = "检索共命中 " + lHitCount.ToString() + " 条,已装入 " + lStart.ToString() + " 条," + strError; return -1; } if (lRet == 0) { return 0; } // 处理浏览结果 foreach (DigitalPlatform.LibraryClient.localhost.Record searchresult in searchresults) { // DigitalPlatform.LibraryClient.localhost.Record searchresult = searchresults[i]; BiblioLine line = new BiblioLine(); line.BiblioRecPath = searchresult.Path; lines.Add(line); biblio_recpaths.Add(searchresult.Path); } #if NO if (lines.Count >= INSERT_BATCH || ((lStart + searchresults.Length >= lHitCount || lCount - searchresults.Length <= 0) && lines.Count > 0) ) #endif { Debug.Assert(biblio_recpaths.Count == lines.Count, ""); // 2015/11/25 this.Channel.Timeout = new TimeSpan(0, 0, 30); // 获得书目摘要 BiblioLoader loader = new BiblioLoader(); loader.Channel = this.Channel; loader.Stop = this.Progress; loader.Format = "summary"; loader.GetBiblioInfoStyle = GetBiblioInfoStyle.None; loader.RecPaths = biblio_recpaths; loader.Prompt -= new MessagePromptEventHandler(loader_Prompt); loader.Prompt += new MessagePromptEventHandler(loader_Prompt); try { int i = 0; foreach (BiblioItem item in loader) { // this.Progress.SetMessage("正在加入 " + (i + 1).ToString() + "/" + targetLeft.Count.ToString() + " 个书目摘要,可能需要较长时间 ..."); BiblioLine line = lines[i]; if (string.IsNullOrEmpty(item.Content) == false) { if (item.Content.Length > 4000) line.Summary = item.Content.Substring(0, 4000); else line.Summary = item.Content; } i++; } } catch (Exception ex) { strError = "ReportForm {72A00ADB-1F9F-45FA-A31E-6956569045D9} exception: " + ExceptionUtil.GetAutoText(ex); return -1; } biblio_recpaths.Clear(); // 插入一批书目记录 nRet = BiblioLine.AppendBiblioLines( connection, lines, true, // 用 false 可以在测试阶段帮助发现重叠插入问题 out strError); if (nRet == -1) return -1; lIndex += lines.Count; lines.Clear(); } lStart += searchresults.Length; lCount -= searchresults.Length; // lIndex += searchresults.Length; lProgress += searchresults.Length; // stop.SetProgressValue(lProgress); SetProgress(lProgress); stop.SetMessage(strBiblioDbNameParam + " " + lStart.ToString() + "/" + lHitCount.ToString() + " " + GetProgressTimeString(lProgress)); if (lStart >= lHitCount || lCount <= 0) break; } if (lines.Count > 0) { Debug.Assert(false, ""); } } finally { this.DeleteResultSet(strResultSetName); } return 0; } } // 从计划文件获得所有分类号检索途径 style internal int GetClassFromStylesFromFile( out List<BiblioDbFromInfo> styles, out string strError) { strError = ""; styles = new List<BiblioDbFromInfo>(); string strBreakPointFileName = Path.Combine(GetBaseDirectory(), "report_breakpoint.xml"); XmlDocument task_dom = new XmlDocument(); try { task_dom.Load(strBreakPointFileName); } catch (FileNotFoundException) { return 0; } catch (Exception ex) { strError = "装载文件 '" + strBreakPointFileName + "' 时出错: " + ex.Message; return -1; } return GetClassFromStyles( task_dom.DocumentElement, out styles, out strError); } // 从计划文件获得所有分类号检索途径 style internal int GetClassFromStylesFromFile(out List<string> styles, out string strError) { strError = ""; styles = new List<string>(); string strBreakPointFileName = Path.Combine(GetBaseDirectory(), "report_breakpoint.xml"); XmlDocument task_dom = new XmlDocument(); try { task_dom.Load(strBreakPointFileName); } catch (FileNotFoundException) { return 0; } catch (Exception ex) { strError = "装载文件 '" + strBreakPointFileName + "' 时出错: " + ex.Message; return -1; } return GetClassFromStyles( task_dom.DocumentElement, out styles, out strError); } // 从计划文件中获得所有分类号检索途径 style internal int GetClassFromStyles( XmlElement root, out List<string> styles, out string strError) { strError = ""; styles = new List<string>(); XmlNodeList nodes = root.SelectNodes("classStyles/style"); foreach (XmlElement element in nodes) { styles.Add(element.GetAttribute("style")); } return 0; } // 从计划文件中获得所有分类号检索途径 style internal int GetClassFromStyles( XmlElement root, out List<BiblioDbFromInfo> styles, out string strError) { strError = ""; styles = new List<BiblioDbFromInfo>(); XmlNodeList nodes = root.SelectNodes("classStyles/style"); foreach (XmlElement element in nodes) { BiblioDbFromInfo info = new BiblioDbFromInfo(); info.Caption = element.GetAttribute("caption"); info.Style = element.GetAttribute("style"); styles.Add(info); } return 0; } // 记忆书目库的分类号 style 列表 int MemoryClassFromStyles(XmlElement root, out string strError) { strError = ""; List<BiblioDbFromInfo> styles = null; int nRet = GetClassFromStylesFromMainform(out styles, out strError); if (nRet == -1) return -1; if (styles.Count == 0) { strError = "书目库尚未配置分类号检索点"; return 0; } XmlElement container = root.SelectSingleNode("classStyles") as XmlElement; if (container == null) { container = root.OwnerDocument.CreateElement("classStyles"); root.AppendChild(container); } else container.RemoveAll(); foreach (BiblioDbFromInfo info in styles) { XmlElement style_element = root.OwnerDocument.CreateElement("style"); container.AppendChild(style_element); style_element.SetAttribute("style", info.Style); style_element.SetAttribute("caption", info.Caption); } return 1; } // 获得所有分类号检索途径 style internal int GetClassFromStylesFromMainform( out List<BiblioDbFromInfo> styles, out string strError) { strError = ""; styles = new List<BiblioDbFromInfo>(); for (int i = 0; i < Program.MainForm.BiblioDbFromInfos.Length; i++) { BiblioDbFromInfo info = Program.MainForm.BiblioDbFromInfos[i]; if (StringUtil.IsInList("__class", info.Style) == true) { string strStyle = GetPureStyle(info.Style); if (string.IsNullOrEmpty(strStyle) == true) { strError = "检索途径 " + info.Caption + " 的 style 值 '" + info.Style + "' 其中应该有至少一个不带 '_' 前缀的子串"; return -1; } BiblioDbFromInfo style = new BiblioDbFromInfo(); style.Caption = info.Caption; style.Style = strStyle; styles.Add(style); } } return 0; } #if NO // 获得所有分类号检索途径 style internal int GetClassFromStyles(out List<string> styles, out string strError) { strError = ""; styles = new List<string>(); for (int i = 0; i < Program.MainForm.BiblioDbFromInfos.Length; i++) { BiblioDbFromInfo info = Program.MainForm.BiblioDbFromInfos[i]; if (StringUtil.IsInList("__class", info.Style) == true) { string strStyle = GetPureStyle(info.Style); if (string.IsNullOrEmpty(strStyle) == true) { strError = "检索途径 "+info.Caption+" 的 style 值 '"+info.Style+"' 其中应该有至少一个不带 '_' 前缀的子串"; return -1; } styles.Add(strStyle); } } return 0; } #endif // 获得不是 _ 和 __ 打头的 style 值 static string GetPureStyle(string strText) { List<string> results = new List<string>(); string[] parts = strText.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in parts) { if (s[0] == '_') continue; results.Add(s); } return StringUtil.MakePathList(results); } // 复制分类号条目 int BuildClassRecords( string strBiblioDbNameParam, string strClassFromStyle, string strClassTableName, long lOldCount, ref long lProgress, ref long lIndex, out string strError) { strError = ""; int nRet = 0; lProgress += lIndex; using (SQLiteConnection connection = new SQLiteConnection(this._connectionString)) { connection.Open(); string strQueryXml = ""; // 采用全局结果集 string strResultSetName = GetResultSetName(); try { this.Channel.Timeout = TimeSpan.FromMinutes(5); // 2018/5/10 long lRet = this.Channel.SearchBiblio(stop, strBiblioDbNameParam, "", // -1, strClassFromStyle, // "__id", "left", // this.textBox_queryWord.Text == "" ? "left" : "exact", // 原来为left 2007/10/18 changed "zh", strResultSetName, "", // strSearchStyle "keyid", //strOutputStyle, // (bOutputKeyCount == true ? "keycount" : ""), "", out strQueryXml, out strError); if (lRet == -1) { if (this.Channel.ErrorCode == ErrorCode.FromNotFound) return 0; return -1; } if (lRet == 0) return 0; long lHitCount = lRet; AdjustProgressRange(lOldCount, lHitCount); long lStart = lIndex; long lCount = lHitCount - lIndex; DigitalPlatform.LibraryClient.localhost.Record[] searchresults = null; // string strStyle = "id,cols,format:@coldef:*/barcode|*/department|*/readerType|*/name"; string strStyle = "keyid,id,key"; // 装入浏览格式 List<ClassLine> lines = new List<ClassLine>(); for (; ; ) { if (this.InvokeRequired == false) Application.DoEvents(); // 出让界面控制权 if (stop != null && stop.State != 0) { strError = "检索共命中 " + lHitCount.ToString() + " 条,已装入 " + lStart.ToString() + " 条,用户中断..."; return -1; } lRet = this.Channel.GetSearchResult( stop, strResultSetName, lStart, lCount, strStyle, // bOutputKeyCount == true ? "keycount" : "id,cols", "zh", out searchresults, out strError); if (lRet == -1) { strError = "检索共命中 " + lHitCount.ToString() + " 条,已装入 " + lStart.ToString() + " 条," + strError; return -1; } if (lRet == 0) { return 0; } // 处理浏览结果 foreach (DigitalPlatform.LibraryClient.localhost.Record searchresult in searchresults) { // DigitalPlatform.LibraryClient.localhost.Record searchresult = searchresults[i]; ClassLine line = new ClassLine(); line.BiblioRecPath = searchresult.Path; if (searchresult.Keys != null && searchresult.Keys.Length > 0) line.Class = searchresult.Keys[0].Key; lines.Add(line); } #if NO if (lines.Count >= INSERT_BATCH || ((lStart + searchresults.Length >= lHitCount || lCount - searchresults.Length <= 0) && lines.Count > 0) ) #endif { // 插入一批分类号记录 nRet = ClassLine.AppendClassLines( connection, strClassTableName, lines, out strError); if (nRet == -1) return -1; lIndex += lines.Count; lines.Clear(); } lStart += searchresults.Length; lCount -= searchresults.Length; // lIndex += searchresults.Length; lProgress += searchresults.Length; // stop.SetProgressValue(lProgress); SetProgress(lProgress); stop.SetMessage(strBiblioDbNameParam + " " + strClassFromStyle + " " + lStart.ToString() + "/" + lHitCount.ToString() + " " + GetProgressTimeString(lProgress)); if (lStart >= lHitCount || lCount <= 0) break; } if (lines.Count > 0) { Debug.Assert(false, ""); } } finally { this.DeleteResultSet(strResultSetName); } return 0; } } #if NO // TODO strCfgFile 修改为使用 writer // 输出 Excel 报表文件 // return: // -1 出错 // 0 没有创建文件(因为输出的表格为空) // 1 成功创建文件 int OutputExcelReport( Table table, string strCfgFile, Hashtable macro_table, string strOutputFileName, out string strError) { strError = ""; XmlDocument dom = new XmlDocument(); try { dom.Load(strCfgFile); } catch (FileNotFoundException) { strError = "配置文件 '" + strCfgFile + "' 没有找到"; return -1; } catch (Exception ex) { strError = "报表配置文件 " + strCfgFile + " 打开错误: " + ex.Message; return -1; } List<bool> sums = new List<bool>(); string strColumDefString = ""; XmlNodeList nodes = dom.DocumentElement.SelectNodes("columns/column"); foreach (XmlNode node in nodes) { string strName = DomUtil.GetAttr(node, "name"); string strAlign = DomUtil.GetAttr(node, "align"); string strSum = DomUtil.GetAttr(node, "sum"); bool bSum = StringUtil.GetBooleanValue(strSum, false); sums.Add(bSum); if (string.IsNullOrEmpty(strColumDefString) == false) strColumDefString += ","; strColumDefString += strName; } string strTitle = DomUtil.GetElementText(dom.DocumentElement, "title").Replace("\\r", "|"); string strTitleComment = DomUtil.GetElementText(dom.DocumentElement, "titleComment").Replace("\\r", "|"); string strColumnSortStyle = DomUtil.GetElementText(dom.DocumentElement, "columnSortStyle"); strTitle = Global.MacroString(macro_table, strTitle); strTitleComment = Global.MacroString(macro_table, strTitleComment); List<string> title_lines = StringUtil.SplitList(strTitle, '|'); List<string> title_comment_lines = StringUtil.SplitList(strTitleComment, '|'); Report report = Report.BuildReport(table, strColumDefString, // "部门||department,借书(册)||borrowitem", "", false); if (report == null) return 0; int i = 0; foreach (PrintColumn column in report) { if (i >= sums.Count) break; // 因为 Columns 因为 hint 的缘故,可能会比这里定义的要多 column.Sum = sums[i]; i++; } // 写入输出文件 if (string.IsNullOrEmpty(strOutputFileName) == true) strOutputFileName = this.NewOutputFileName(); else { // 确保目录被创建 PathUtil.CreateDirIfNeed(Path.GetDirectoryName(strOutputFileName)); } ExcelDocument doc = null; doc = ExcelDocument.Create(strOutputFileName); try { doc.NewSheet("Sheet1"); // 输出标题文字 int nColIndex = 0; int _lineIndex = 0; foreach (string t in title_lines) { List<CellData> cells = new List<CellData>(); cells.Add(new CellData(nColIndex, t)); doc.WriteExcelLine(_lineIndex, cells); #if NO doc.WriteExcelCell( _lineIndex, nColIndex, t, true); #endif _lineIndex++; } foreach (string t in title_comment_lines) { List<CellData> cells = new List<CellData>(); cells.Add(new CellData(nColIndex, t)); doc.WriteExcelLine(_lineIndex, cells); #if NO doc.WriteExcelCell( _lineIndex, nColIndex, t, true); #endif _lineIndex++; } // 输出 Excel 格式的表格 // parameters: // nTopLines 顶部预留多少行 report.OutputExcelTable(table, doc, title_lines.Count + title_comment_lines.Count + 1, -1); doc.SaveWorksheet(); } finally { if (doc != null) { doc.Close(); doc = null; } } // File.SetAttributes(strOutputFileName, FileAttributes.Archive); return 1; } #endif #if NO static void WriteTitles(XmlTextWriter writer, string strTitleString) { List<string> titles = StringUtil.SplitList(strTitleString, '\r'); WriteTitles(writer, titles); } static void WriteTitles(XmlTextWriter writer, List<string> titles) { int i = 0; foreach (string title in titles) { if (i > 0) writer.WriteElementString("br", ""); writer.WriteString(title); i++; } } #endif #if NO // 根据一个表格按照缺省特性创建一个Report对象 // parameters: // strDefaultValue 全部列的缺省值 // null表示不改变缺省值"",否则为strDefaultValue指定的值 // bSum 是否全部列都要参加合计 // bContentColumn 是否考虑内容行中比指定的栏目多出来的栏目 public static Report BuildReport(SQLiteDataReader table, string strColumnTitles, string strDefaultValue, bool bSum, bool bContentColumn = true) { // Debug.Assert(false, ""); if (table.HasRows == false) return null; // 无法创建。内容必须至少一行以上 Report report = new Report(); // Line line = table.FirstHashLine(); // 随便得到一行。这样不要求table排过序 // 列标题 { PrintColumn column = new PrintColumn(); column.ColumnNumber = -1; report.Add(column); } int nTitleCount = 0; if (strColumnTitles != null) { string[] aName = strColumnTitles.Split(new Char[] { ',' }); nTitleCount = aName.Length; } int nColumnCount = nTitleCount; if (bContentColumn == true) nColumnCount = Math.Max(table.FieldCount, nTitleCount); // 检查表格第一行 // 因为列标题column已经加入,所以现在最多加入nTitleCount-1栏 for (int i = 0; i < nColumnCount - 1; i++) { PrintColumn column = new PrintColumn(); column.ColumnNumber = i; if (strDefaultValue != null) column.DefaultValue = strDefaultValue; column.Sum = bSum; report.Add(column); } // 添加列标题 if (strColumnTitles != null) { string[] aName = strColumnTitles.Split(new Char[] { ',' }); /* if (aName.Length < report.Count) { string strError = "列定义 '" + strColumnTitles + "' 中的列数 " + aName.Length.ToString() + "小于报表实际最大列数 " + report.Count.ToString(); throw new Exception(strError); }*/ int j = 0; for (j = 0; j < report.Count; j++) { // 2007/10/26 if (j >= aName.Length) break; string strText = ""; strText = aName[j]; string strNameText = ""; string strNameClass = ""; int nRet = strText.IndexOf("||"); if (nRet == -1) strNameText = strText; else { strNameText = strText.Substring(0, nRet); strNameClass = strText.Substring(nRet + 2); } PrintColumn column = (PrintColumn)report[j]; if (j < aName.Length) { column.Title = strNameText; column.CssClass = strNameClass; } } } report.SumLine = bSum; // 计算 colspan PrintColumn current = null; foreach (PrintColumn column in report) { if (string.IsNullOrEmpty(column.Title) == false && column.Title[0] == '+' && current != null) { column.Colspan = 0; // 表示这是一个从属的列 current.Colspan++; } else current = column; } return report; } #endif #if NO static Jurassic.ScriptEngine engine = null; // 输出 RML 格式的表格 // 本函数负责写入 <table> 元素 // parameters: // nTopLines 顶部预留多少行 public void OutputRmlTable( Report report, SQLiteDataReader table, XmlTextWriter writer, int nMaxLines = -1) { // StringBuilder strResult = new StringBuilder(4096); int i, j; #if NO if (nMaxLines == -1) nMaxLines = table.Count; #endif writer.WriteStartElement("table"); writer.WriteAttributeString("class", "table"); writer.WriteStartElement("thead"); writer.WriteStartElement("tr"); int nEvalCount = 0; // 具有 eval 的栏目个数 for (j = 0; j < report.Count; j++) { PrintColumn column = (PrintColumn)report[j]; if (column.Colspan == 0) continue; if (string.IsNullOrEmpty(column.Eval) == false) nEvalCount++; writer.WriteStartElement("th"); if (string.IsNullOrEmpty(column.CssClass) == false) writer.WriteAttributeString("class", column.CssClass); if (column.Colspan > 1) writer.WriteAttributeString("colspan", column.Colspan.ToString()); writer.WriteString(column.Title); writer.WriteEndElement(); // </th> } writer.WriteEndElement(); // </tr> writer.WriteEndElement(); // </thead> // 合计数组 object[] sums = null; // 2008/12/1 new changed if (report.SumLine) { sums = new object[report.Count]; for (i = 0; i < sums.Length; i++) { sums[i] = null; } } NumberFormatInfo nfi = new CultureInfo("zh-CN", false).NumberFormat; nfi.NumberDecimalDigits = 2; writer.WriteStartElement("tbody"); // Jurassic.ScriptEngine engine = null; if (nEvalCount > 0 && engine == null) { engine = new Jurassic.ScriptEngine(); engine.EnableExposedClrTypes = true; } // 内容行循环 for (i = 0; ; i++) // i < Math.Min(nMaxLines, table.Count) { if (table.HasRows == false) break; // Line line = table[i]; if (engine != null) engine.SetGlobalValue("reader", table); string strLineCssClass = "content"; #if NO if (report.OutputLine != null) { OutputLineEventArgs e = new OutputLineEventArgs(); e.Line = line; e.Index = i; e.LineCssClass = strLineCssClass; report.OutputLine(this, e); if (e.Output == false) continue; strLineCssClass = e.LineCssClass; } #endif // strResult.Append("<tr class='" + strLineCssClass + "'>\r\n"); writer.WriteStartElement("tr"); writer.WriteAttributeString("class", strLineCssClass); // 列循环 for (j = 0; j < report.Count; j++) { PrintColumn column = (PrintColumn)report[j]; if (column.ColumnNumber < -1) { throw (new Exception("PrintColumn对象ColumnNumber列尚未初始化,位置" + Convert.ToString(j))); } string strText = ""; if (column.ColumnNumber != -1) { if (string.IsNullOrEmpty(column.Eval) == false) { // engine.SetGlobalValue("cell", line.GetObject(column.ColumnNumber)); strText = engine.Evaluate(column.Eval).ToString(); } else if (column.DataType == DataType.PriceDouble) { if (table.IsDBNull(column.ColumnNumber /**/) == true) strText = column.DefaultValue; else { double v = table.GetDouble(column.ColumnNumber); /* NumberFormatInfo provider = new NumberFormatInfo(); provider.NumberDecimalDigits = 2; provider.NumberGroupSeparator = "."; provider.NumberGroupSizes = new int[] { 3 }; strText = Convert.ToString(v, provider); * */ strText = v.ToString("N", nfi); } } else if (column.DataType == DataType.PriceDecimal) { if (table.IsDBNull(column.ColumnNumber) == true) strText = column.DefaultValue; else { decimal v = table.GetDecimal(column.ColumnNumber); strText = v.ToString("N", nfi); } } else if (column.DataType == DataType.PriceDecimal) { if (table.IsDBNull(column.ColumnNumber) == true) strText = column.DefaultValue; else { decimal v = table.GetDecimal(column.ColumnNumber); strText = v.ToString("N", nfi); } } else if (column.DataType == DataType.Price) { // Debug.Assert(false, ""); if (table.IsDBNull(column.ColumnNumber) == true) strText = column.DefaultValue; // 2005/5/26 else strText = table.GetString(column.ColumnNumber); // } else strText = table.GetString(column.ColumnNumber/*, column.DefaultValue*/); } else { strText = table.GetString(0); // line.Entry; } writer.WriteStartElement(j == 0 ? "th" : "td"); if (string.IsNullOrEmpty(column.CssClass) == false) writer.WriteAttributeString("class", column.CssClass); writer.WriteString(strText); writer.WriteEndElement(); // </td> if (report.SumLine == true && column.Sum == true && column.ColumnNumber != -1) { try { // if (column.DataType != DataType.Currency) { object v = table.GetValue(column.ColumnNumber); #if NO if (report.SumCell != null) { SumCellEventArgs e = new SumCellEventArgs(); e.DataType = column.DataType; e.ColumnNumber = column.ColumnNumber; e.LineIndex = i; e.Line = line; e.Value = v; report.SumCell(this, e); if (e.Value == null) continue; v = e.Value; } #endif if (sums[j] == null) sums[j] = v; else { sums[j] = AddValue(column.DataType, sums[j], v); // sums[j] = ((decimal)sums[j]) + v; } } } catch (Exception ex) // 俘获可能因字符串转换为整数抛出的异常 { throw new Exception("在累加 行 " + i.ToString() + " 列 " + column.ColumnNumber.ToString() + " 值的时候,抛出异常: " + ex.Message); } } } // strResult.Append("</tr>\r\n"); writer.WriteEndElement(); // </tr> } writer.WriteEndElement(); // </tbody> if (report.SumLine == true) { Line sum_line = null; if (engine != null) { // 准备 Line 对象 sum_line = new Line(0); for (j = 1; j < report.Count; j++) { PrintColumn column = (PrintColumn)report[j]; if (column.Sum == true && sums[j] != null) { sum_line.SetValue(j - 1, sums[j]); } } engine.SetGlobalValue("line", sum_line); } // strResult.Append("<tr class='sum'>\r\n"); writer.WriteStartElement("tfoot"); writer.WriteStartElement("tr"); writer.WriteAttributeString("class", "sum"); for (j = 0; j < report.Count; j++) { PrintColumn column = (PrintColumn)report[j]; string strText = ""; if (j == 0) strText = "合计"; else if (string.IsNullOrEmpty(column.Eval) == false) { strText = engine.Evaluate(column.Eval).ToString(); } else if (column.Sum == true && sums[j] != null) { if (column.DataType == DataType.PriceDouble) strText = ((double)sums[j]).ToString("N", nfi); else if (column.DataType == DataType.PriceDecimal) strText = ((decimal)sums[j]).ToString("N", nfi); else if (column.DataType == DataType.Price) { strText = StatisUtil.Int64ToPrice((Int64)sums[j]); } else strText = Convert.ToString(sums[j]); if (column.DataType == DataType.Currency) { string strSomPrice = ""; string strError = ""; // 汇总价格 int nRet = PriceUtil.SumPrices(strText, out strSomPrice, out strError); if (nRet == -1) strText = strError; else strText = strSomPrice; } } else strText = column.DefaultValue; // "&nbsp;"; #if NO doc.WriteExcelCell( _lineIndex, j, strText, true); #endif writer.WriteStartElement(j == 0 ? "th" : "td"); if (string.IsNullOrEmpty(column.CssClass) == false) writer.WriteAttributeString("class", column.CssClass); writer.WriteString(strText); writer.WriteEndElement(); // </td> } // strResult.Append("</tr>\r\n"); writer.WriteEndElement(); // </tr> writer.WriteEndElement(); // </tfoot> } writer.WriteEndElement(); // </table> } object AddValue(DataType datatype, object o1, object o2) { if (o1 == null && o2 == null) return null; if (o1 == null) return o2; if (o2 == null) return o1; if (datatype == DataType.Auto) { if (o1 is Int64) return (Int64)o1 + (Int64)o2; if (o1 is Int32) return (Int32)o1 + (Int32)o2; if (o1 is double) return (double)o1 + (double)o2; if (o1 is decimal) return (decimal)o1 + (decimal)o2; if (o1 is string) return (string)o1 + (string)o2; throw new Exception("无法支持的 Auto 类型累加"); } if (datatype == DataType.Number) { if (o1 is Int64) return (Int64)o1 + (Int64)o2; if (o1 is Int32) return (Int32)o1 + (Int32)o2; if (o1 is double) return (double)o1 + (double)o2; if (o1 is decimal) return (decimal)o1 + (decimal)o2; throw new Exception("无法支持的 Number 类型累加"); } if (datatype == DataType.String) { if (o1 is string) return (string)o1 + (string)o2; throw new Exception("无法支持的 String 类型累加"); } if (datatype == DataType.Price) // 100倍金额整数 { return (Int64)o1 + (Int64)o2; } if (datatype == DataType.PriceDouble) // double,用来表示金额。也就是最多只有两位小数部分 -- 注意,有累计误差问题,以后建议废止 { return (double)o1 + (double)o2; } if (datatype == DataType.PriceDecimal) // decimal,用来表示金额。 { return (decimal)o1 + (decimal)o2; } if (datatype == DataType.Currency) { // 这一举容易发现列 数据类型 的错误 return PriceUtil.JoinPriceString((string)o1, (string)o2); #if NO // 这一句更健壮一些 return PriceUtil.JoinPriceString(Convert.ToString(o1), Convert.ToString(o2)); #endif } throw new Exception("无法支持的 " + datatype.ToString() + " 类型累加"); } #endif #if NO // 输出 RML 报表文件 // return: // -1 出错 // 0 没有创建文件(因为输出的表格为空) // 1 成功创建文件 int OutputRmlReport( SQLiteDataReader table, string strCfgFile, Hashtable macro_table, string strOutputFileName, out string strError) { strError = ""; XmlDocument dom = new XmlDocument(); try { dom.Load(strCfgFile); } catch (FileNotFoundException) { strError = "配置文件 '" + strCfgFile + "' 没有找到"; return -1; } catch (Exception ex) { strError = "报表配置文件 " + strCfgFile + " 打开错误: " + ex.Message; return -1; } XmlDocument columns_dom = null; List<bool> sums = new List<bool>(); string strColumDefString = ""; XmlNodeList nodes = dom.DocumentElement.SelectNodes("columns/column"); if (nodes.Count > 0) { columns_dom = new XmlDocument(); columns_dom.AppendChild(columns_dom.CreateElement("columns")); } List<string> evals = new List<string>(); { int i = 0; foreach (XmlNode node in nodes) { string strName = DomUtil.GetAttr(node, "name"); string strAlign = DomUtil.GetAttr(node, "align"); string strSum = DomUtil.GetAttr(node, "sum"); string strClass = DomUtil.GetAttr(node, "class"); string strEval = DomUtil.GetAttr(node, "eval"); evals.Add(strEval); if (string.IsNullOrEmpty(strClass) == true) strClass = "c" + (i + 1).ToString(); bool bSum = StringUtil.GetBooleanValue(strSum, false); sums.Add(bSum); if (string.IsNullOrEmpty(strColumDefString) == false) strColumDefString += ","; strColumDefString += strName + "||" + strClass; XmlElement column = columns_dom.CreateElement("column"); columns_dom.DocumentElement.AppendChild(column); column.SetAttribute("class", strClass); column.SetAttribute("align", strAlign); i++; } } string strTitle = DomUtil.GetElementText(dom.DocumentElement, "title").Replace("\\r", "\r"); strTitle = Global.MacroString(macro_table, strTitle); string strComment = DomUtil.GetElementText(dom.DocumentElement, "titleComment").Replace("\\r", "\r"); strComment = Global.MacroString(macro_table, strComment); #if NO Report report = Report.BuildReport(table, strColumDefString, // "部门||department,借书(册)||borrowitem", "", true, false); // 不包括内容中多余的列 #endif Report report = BuildReport(table, strColumDefString, // "部门||department,借书(册)||borrowitem", "", true, false); // 不包括内容中多余的列 if (report == null) return 0; { int i = 0; foreach (PrintColumn column in report) { if (i >= sums.Count) break; // 因为 Columns 因为 hint 的缘故,可能会比这里定义的要多 column.Eval = evals[i]; column.Sum = sums[i]; i++; } } string strCreateTime = DateTime.Now.ToString(); string strCssContent = DomUtil.GetElementText(dom.DocumentElement, "css").Replace("\\r", "\r\n").Replace("\\t", "\t"); // 写入输出文件 if (string.IsNullOrEmpty(strOutputFileName) == true) { Debug.Assert(false, ""); strOutputFileName = this.NewOutputFileName(); } else { // 确保目录被创建 PathUtil.CreateDirIfNeed(Path.GetDirectoryName(strOutputFileName)); } using (XmlTextWriter writer = new XmlTextWriter(strOutputFileName, Encoding.UTF8)) { writer.Formatting = Formatting.Indented; writer.Indentation = 4; writer.WriteStartDocument(); writer.WriteStartElement("report"); writer.WriteAttributeString("version", "0.01"); writer.WriteStartElement("title"); WriteTitles(writer, strTitle); writer.WriteEndElement(); writer.WriteStartElement("comment"); WriteTitles(writer, strComment); writer.WriteEndElement(); writer.WriteStartElement("createTime"); writer.WriteString(strCreateTime); writer.WriteEndElement(); if (string.IsNullOrEmpty(strCssContent) == false) { writer.WriteStartElement("style"); writer.WriteCData("\r\n" + strCssContent + "\r\n"); writer.WriteEndElement(); } // XmlNode node = dom.DocumentElement.SelectSingleNode("columns"); if (columns_dom != null && columns_dom.DocumentElement != null) columns_dom.DocumentElement.WriteTo(writer); // 写入输出文件 if (string.IsNullOrEmpty(strOutputFileName) == true) strOutputFileName = this.NewOutputFileName(); else { // 确保目录被创建 PathUtil.CreateDirIfNeed(Path.GetDirectoryName(strOutputFileName)); } OutputRmlTable( report, table, writer); writer.WriteEndElement(); // </report> writer.WriteEndDocument(); } File.SetAttributes(strOutputFileName, FileAttributes.Archive); #if NO string strHtmlFileName = Path.Combine(Path.GetDirectoryName(strOutputFileName), Path.GetFileNameWithoutExtension(strOutputFileName) + ".html"); int nRet = Report.RmlToHtml(strOutputFileName, strHtmlFileName, out strError); if (nRet == -1) return -1; #endif return 1; } // 输出 RML 报表文件 // return: // -1 出错 // 0 没有创建文件(因为输出的表格为空) // 1 成功创建文件 int OutputRmlReport( Table table, string strCfgFile, Hashtable macro_table, string strOutputFileName, out string strError) { strError = ""; XmlDocument dom = new XmlDocument(); try { dom.Load(strCfgFile); } catch (FileNotFoundException) { strError = "配置文件 '" + strCfgFile + "' 没有找到"; return -1; } catch (Exception ex) { strError = "报表配置文件 " + strCfgFile + " 打开错误: " + ex.Message; return -1; } XmlDocument columns_dom = null; List<bool> sums = new List<bool>(); string strColumDefString = ""; XmlNodeList nodes = dom.DocumentElement.SelectNodes("columns/column"); if (nodes.Count > 0) { columns_dom = new XmlDocument(); columns_dom.AppendChild(columns_dom.CreateElement("columns")); } List<string> evals = new List<string>(); { int i = 0; foreach (XmlNode node in nodes) { string strName = DomUtil.GetAttr(node, "name"); string strAlign = DomUtil.GetAttr(node, "align"); string strSum = DomUtil.GetAttr(node, "sum"); string strClass = DomUtil.GetAttr(node, "class"); string strEval = DomUtil.GetAttr(node, "eval"); evals.Add(strEval); if (string.IsNullOrEmpty(strClass) == true) strClass = "c" + (i + 1).ToString(); bool bSum = StringUtil.GetBooleanValue(strSum, false); sums.Add(bSum); if (string.IsNullOrEmpty(strColumDefString) == false) strColumDefString += ","; strColumDefString += strName + "||" + strClass; XmlElement column = columns_dom.CreateElement("column"); columns_dom.DocumentElement.AppendChild(column); column.SetAttribute("class", strClass); column.SetAttribute("align", strAlign); i++; } } string strTitle = DomUtil.GetElementText(dom.DocumentElement, "title").Replace("\\r", "\r"); strTitle = Global.MacroString(macro_table, strTitle); string strComment = DomUtil.GetElementText(dom.DocumentElement, "titleComment").Replace("\\r", "\r"); strComment = Global.MacroString(macro_table, strComment); Report report = Report.BuildReport(table, strColumDefString, // "部门||department,借书(册)||borrowitem", "", true, false); // 不包括内容中多余的列 if (report == null) return 0; { int i = 0; foreach (PrintColumn column in report) { if (i >= sums.Count) break; // 因为 Columns 因为 hint 的缘故,可能会比这里定义的要多 column.Eval = evals[i]; column.Sum = sums[i]; i++; } } string strCreateTime = DateTime.Now.ToString(); string strCssContent = DomUtil.GetElementText(dom.DocumentElement, "css").Replace("\\r", "\r\n").Replace("\\t", "\t"); // 写入输出文件 if (string.IsNullOrEmpty(strOutputFileName) == true) { Debug.Assert(false, ""); strOutputFileName = this.NewOutputFileName(); } else { // 确保目录被创建 PathUtil.CreateDirIfNeed(Path.GetDirectoryName(strOutputFileName)); } using (XmlTextWriter writer = new XmlTextWriter(strOutputFileName, Encoding.UTF8)) { writer.Formatting = Formatting.Indented; writer.Indentation = 4; writer.WriteStartDocument(); writer.WriteStartElement("report"); writer.WriteAttributeString("version", "0.01"); writer.WriteStartElement("title"); WriteTitles(writer, strTitle); writer.WriteEndElement(); writer.WriteStartElement("comment"); WriteTitles(writer, strComment); writer.WriteEndElement(); writer.WriteStartElement("createTime"); writer.WriteString(strCreateTime); writer.WriteEndElement(); if (string.IsNullOrEmpty(strCssContent) == false) { writer.WriteStartElement("style"); writer.WriteCData("\r\n" + strCssContent + "\r\n"); writer.WriteEndElement(); } // XmlNode node = dom.DocumentElement.SelectSingleNode("columns"); if (columns_dom != null && columns_dom.DocumentElement != null) columns_dom.DocumentElement.WriteTo(writer); // 写入输出文件 if (string.IsNullOrEmpty(strOutputFileName) == true) strOutputFileName = this.NewOutputFileName(); else { // 确保目录被创建 PathUtil.CreateDirIfNeed(Path.GetDirectoryName(strOutputFileName)); } report.OutputRmlTable(table, writer); writer.WriteEndElement(); // </report> writer.WriteEndDocument(); } File.SetAttributes(strOutputFileName, FileAttributes.Archive); #if NO string strHtmlFileName = Path.Combine(Path.GetDirectoryName(strOutputFileName), Path.GetFileNameWithoutExtension(strOutputFileName) + ".html"); int nRet = Report.RmlToHtml(strOutputFileName, strHtmlFileName, out strError); if (nRet == -1) return -1; #endif return 1; } #endif #if NO // TODO writer // 输出 HTML 报表文件 // return: // -1 出错 // 0 没有创建文件(因为输出的表格为空) // 1 成功创建文件 int OutputHtmlReport1( Table table, string strCfgFile, Hashtable macro_table, string strOutputFileName, out string strError) { strError = ""; XmlDocument dom = new XmlDocument(); try { dom.Load(strCfgFile); } catch (FileNotFoundException) { strError = "配置文件 '" + strCfgFile + "' 没有找到"; return -1; } catch (Exception ex) { strError = "报表配置文件 " + strCfgFile + " 打开错误: " + ex.Message; return -1; } List<bool> sums = new List<bool>(); string strColumDefString = ""; XmlNodeList nodes = dom.DocumentElement.SelectNodes("columns/column"); foreach (XmlNode node in nodes) { string strName = DomUtil.GetAttr(node, "name"); string strAlign = DomUtil.GetAttr(node, "align"); string strSum = DomUtil.GetAttr(node, "sum"); string strClass = DomUtil.GetAttr(node, "class"); bool bSum = StringUtil.GetBooleanValue(strSum, false); sums.Add(bSum); if (string.IsNullOrEmpty(strColumDefString) == false) strColumDefString += ","; strColumDefString += strName + "||" +strClass; } string strTitle = DomUtil.GetElementText(dom.DocumentElement, "title").Replace("\\r", "<br/>"); string strTitleComment = DomUtil.GetElementText(dom.DocumentElement, "titleComment").Replace("\\r", "<br/>"); strTitle = Global.MacroString(macro_table, strTitle); strTitleComment = Global.MacroString(macro_table, strTitleComment); Report report = Report.BuildReport(table, strColumDefString, // "部门||department,借书(册)||borrowitem", "&nbsp;", true); if (report == null) return 0; int i = 0; foreach (PrintColumn column in report) { if (i >= sums.Count) break; // 因为 Columns 因为 hint 的缘故,可能会比这里定义的要多 column.Sum = sums[i]; i++; } string strCreateTime = HttpUtility.HtmlEncode("报表创建时间 " + DateTime.Now.ToString()); // string strCssFileName = ""; string strCssContent = DomUtil.GetElementText(dom.DocumentElement, "css").Replace("\\r", "\r\n").Replace("\\t", "\t"); string strHead = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head>" + "<meta http-equiv='Content-Type' content=\"text/html; charset=utf-8\">" + "<title>"+strTitle.Replace("<br/>", " ")+"</title>" // + "<link rel='stylesheet' href='"+strCssFileName+"' type='text/css'>" + "<style media='screen' type='text/css'>" + strCssContent + "</style>" + "</head><body>" + "<div class='tabletitle'>" + strTitle + "</div>" + "<div class='titlecomment'>" + strTitleComment + "</div>"; string strTail = "<div class='createtime'>"+strCreateTime+"</div></body></html>"; string strHtml = strHead + report.HtmlTable(table) + strTail; // 写入输出文件 if (string.IsNullOrEmpty(strOutputFileName) == true) strOutputFileName = this.NewOutputFileName(); else { // 确保目录被创建 PathUtil.CreateDirIfNeed(Path.GetDirectoryName(strOutputFileName)); } this.WriteToOutputFile(strOutputFileName, strHtml, Encoding.UTF8); // File.SetAttributes(strOutputFileName, FileAttributes.Archive); return 1; } #endif #if NO // 从报表配置文件中获得 <columnSortStyle> 元素文本值 static string GetColumnSortStyle(string strCfgFile) { string strError = ""; XmlDocument dom = new XmlDocument(); try { dom.Load(strCfgFile); } catch (FileNotFoundException) { strError = "配置文件 '" + strCfgFile + "' 没有找到"; return ""; } catch (Exception ex) { strError = "报表配置文件 " + strCfgFile + " 打开错误: " + ex.Message; return ""; } return DomUtil.GetElementText(dom.DocumentElement, "columnSortStyle"); } #endif // 按照指定的单位名称列表,列出借书册数 // return: // -1 出错 // 0 没有创建文件(因为输出的表格为空) // 1 成功创建文件 int Create_102_report(string strLibraryCode, string strDateRange, string strCfgFile, // string strTitle, // 例如: 各年级 Hashtable macro_table, string strNameTable, string strOutputFileName, string strReportType, out string strError) { strError = ""; int nRet = 0; if (strReportType != "102" && strReportType != "9102") { strError = "Create_102_report() 的 strReportType 参数值必须为 102/9102 之一"; return -1; } List<string> departments = StringUtil.SplitList(strNameTable); if (departments.Count == 0) return 0; Table tableDepartment = new Table(3); #if NO foreach (string department in departments) { string strCommand = ""; nRet = CreateReaderReportCommand( strLibraryCode, strDateRange, "102", department, out strCommand, out strError); if (nRet == -1) return -1; nRet = RunQuery( strCommand, ref tableDepartment, out strError); if (nRet == -1) return -1; } #endif List<string> commands = new List<string>(); foreach (string department in departments) { string strCommand = ""; nRet = CreateReaderReportCommand( strLibraryCode, strDateRange, strReportType, // "102", department, out strCommand, out strError); if (nRet == -1) return -1; commands.Add(strCommand); } nRet = RunQuery( commands, ref tableDepartment, out strError); if (nRet == -1) return -1; if (nRet == 0) return 0; // macro_table["%daterange%"] = strDateRange; ReportWriter writer = null; nRet = GetReportWriter(strCfgFile, out writer, out strError); if (nRet == -1) return -1; string strColumnSortStyle = writer.GetColumnSortStyle(); if (string.IsNullOrEmpty(strColumnSortStyle) == true) strColumnSortStyle = "0:d,-1:a"; // 先按照册数从大到小;然后按照名称从小到大 else strColumnSortStyle = SortColumnCollection.NormalToTable(strColumnSortStyle); tableDepartment.Sort(strColumnSortStyle); // 观察表格中是否全部行为 0 for (int i = 0; i < tableDepartment.Count; i++) { Line line = tableDepartment[i]; if (line.GetInt64(0) > 0) goto FOUND; } return 0; FOUND: macro_table["%linecount%"] = tableDepartment.Count.ToString(); macro_table["%daterange%"] = strDateRange; TableReader reader = new TableReader(tableDepartment); return writer.OutputRmlReport( reader, macro_table, strOutputFileName, out strError); #if NO return OutputRmlReport( tableDepartment, strCfgFile, macro_table, strOutputFileName, out strError); #endif } ObjectCache<ReportWriter> _writerCache = new ObjectCache<ReportWriter>(); int GetReportWriter(string strCfgFile, out ReportWriter writer, out string strError) { strError = ""; writer = this._writerCache.FindObject(strCfgFile); if (writer == null) { writer = new ReportWriter(); int nRet = writer.Initial(strCfgFile, out strError); if (nRet == -1) return -1; this._writerCache.SetObject(strCfgFile, writer); } return 0; } // 这是创建到一个子目录(会在子目录中创建很多文件和下级目录),而不是输出到一个文件 // return: // -1 出错 // 0 没有创建目录 // 1 创建了目录 int Create_131_report(string strLibraryCode, string strDateRange, string strCfgFile, // string strTitle, // 例如: 各年级 Hashtable macro_table, // string strNameTable, string strOutputDir, string strReportType, out string strError) { strError = ""; int nRet = 0; // macro_table["%library%"] = strLibraryCode; Table reader_table = null; // 获得一个分馆内读者记录的证条码号和单位名称 nRet = GetAllReaderDepartments( strLibraryCode, ref reader_table, out strError); if (nRet == -1) return -1; if (string.IsNullOrEmpty(strOutputDir) == false) { // 不能使用根目录 string strRoot = Directory.GetDirectoryRoot(strOutputDir); if (PathUtil.IsEqual(strRoot, strOutputDir) == true) { } else PathUtil.DeleteDirectory(strOutputDir); } if (reader_table.Count == 0) { // 下级全部目录此时已经删除 return 0; } ReportWriter writer = null; nRet = GetReportWriter(strCfgFile, out writer, out strError); if (nRet == -1) return -1; #if NO string strColumnSortStyle = writer.GetColumnSortStyle(); if (string.IsNullOrEmpty(strColumnSortStyle) == true) strColumnSortStyle = "1:a"; else strColumnSortStyle = SortColumnCollection.NormalToTable(strColumnSortStyle); #endif reader_table.Sort("1:a,-1:a"); // int nWriteCount = 0; // 创建了多少个具体的报表 // 所有部门目录已经删除,然后再开始创建 // stop.SetProgressRange(0, reader_table.Count); for (int i = 0; i < reader_table.Count; i++) { if (this.InvokeRequired == false) Application.DoEvents(); if (stop != null && stop.State != 0) { strError = "用户中断..."; return -1; } Line line = reader_table[i]; string strReaderBarcode = line.Entry; string strName = line.GetString(0); string strDepartment = line.GetString(1); #if NO string strDepartmentName = strDepartment.Replace(" ", "_"); if (string.IsNullOrEmpty(strDepartmentName) == true) strDepartmentName = "其他部门"; #endif // 2016/4/7 string strDepartmentName = GetValidDepartmentString(strDepartment); string strPureFileName = GetValidPathString(strDepartmentName) + "\\" + GetValidPathString(strReaderBarcode + "_" + strName) + ".rml"; string strOutputFileName = ""; try { strOutputFileName = Path.Combine(strOutputDir, // strLibraryCode + "\\" + strPureFileName); // xlsx } catch (System.ArgumentException ex) { strError = "文件名字符串 '" + strPureFileName + "' 中有非法字符。" + ex.Message; return -1; } stop.SetMessage("正在创建报表文件 " + strOutputFileName + " " + (i + 1).ToString() + "/" + reader_table.Count.ToString() + " ..."); #if NO Table tableList = null; nRet = CreateReaderReport( strLibraryCode, strDateRange, "131", strReaderBarcode, ref tableList, out strError); if (nRet == -1) return -1; tableList.Sort(strColumnSortStyle); // "1:a" 按照借书时间排序 #endif macro_table["%name%"] = strName; macro_table["%department%"] = strDepartment; macro_table["%readerbarcode%"] = strReaderBarcode; // macro_table["%linecount%"] = tableList.Count.ToString(); macro_table["%daterange%"] = strDateRange; List<string> commands = new List<string>(); string strCommand = ""; nRet = CreateReaderReportCommand( strLibraryCode, strDateRange, strReportType, // "131", strReaderBarcode, out strCommand, out strError); if (nRet == -1) return -1; commands.Add(strCommand); nRet = RunQuery( commands, writer, strOutputFileName, macro_table, "创建 " + strReportType + " 表时", out strError); if (nRet == -1) return -1; #if NO nRet = CreateReaderReport( strLibraryCode, strDateRange, "131", strReaderBarcode, writer, strOutputFileName, macro_table, out strError); if (nRet == -1) return -1; #endif // TODO: 没有数据的读者,是否在 index.xml 也创建一个条目? if (nRet == 1) { // 将一个统计文件条目写入到 131 子目录中的 index.xml 的 DOM 中 // parameters: // strOutputDir index.xml 所在目录 nRet = Write_131_IndexXml( strDepartmentName, strName, strReaderBarcode, strOutputDir, strOutputFileName, strReportType, out strError); if (nRet == -1) return -1; nWriteCount++; } } if (nWriteCount > 0 && (this._fileType & FileType.HTML) != 0) { string strIndexXmlFileName = Path.Combine(strOutputDir, "index.xml"); string strIndexHtmlFileName = Path.Combine(strOutputDir, "index.html"); if (stop != null) stop.SetMessage("正在创建 " + strIndexHtmlFileName); // 根据 index.xml 文件创建 index.html 文件 nRet = CreateIndexHtmlFile(strIndexXmlFileName, strIndexHtmlFileName, out strError); if (nRet == -1) return -1; } if (nWriteCount > 0) return 1; return 0; } // 附加的一些文件名非法字符。比如 XP 下 Path.GetInvalidPathChars() 不知何故会遗漏 '*' static string spec_invalid_chars = "*?:"; public static string GetValidPathString(string strText, string strReplaceChar = "_") { if (string.IsNullOrEmpty(strText) == true) return ""; // string invalid_chars = new string(Path.GetInvalidPathChars()); // invalid_chars += "\t"; // 2014/9/19 修改 BUG char[] invalid_chars = Path.GetInvalidPathChars(); StringBuilder result = new StringBuilder(); foreach (char c in strText) { if (c == ' ') continue; if (IndexOf(invalid_chars, c) != -1 || spec_invalid_chars.IndexOf(c) != -1) result.Append(strReplaceChar); else result.Append(c); } return result.ToString(); } static int IndexOf(char[] chars, char c) { int i = 0; foreach (char c1 in chars) { if (c1 == c) return i; i++; } return -1; } public static string GetValidDepartmentString(string strText, string strReplaceChar = "_") { if (strText != null) strText = strText.Trim(); if (string.IsNullOrEmpty(strText) == true) return "其他部门"; // 文件名非法字符 string department_invalid_chars = " /"; StringBuilder result = new StringBuilder(); foreach (char c in strText) { if (c == ' ') continue; if (department_invalid_chars.IndexOf(c) != -1) result.Append(strReplaceChar); else result.Append(c); } return result.ToString(); } // 101 111 121 122 // 121 表 按照读者 *姓名* 分类的借书册数表 // 122 表 按照读者 *姓名* 没有借书的读者 // return: // -1 出错 // 0 没有创建文件(因为输出的表格为空) // 1 成功创建文件 int Create_1XX_report(string strLibraryCode, string strDateRange, string strCfgFile, Hashtable macro_table, string strOutputFileName, string strReportType, out string strError) { strError = ""; // macro_table["%linecount%"] = tableDepartment.Count.ToString(); macro_table["%daterange%"] = strDateRange; ReportWriter writer = null; int nRet = GetReportWriter(strCfgFile, out writer, out strError); if (nRet == -1) return -1; List<string> commands = new List<string>(); string strCommand = ""; nRet = CreateReaderReportCommand( strLibraryCode, strDateRange, strReportType, // "121", "", out strCommand, out strError); if (nRet == -1) return -1; commands.Add(strCommand); return RunQuery( commands, writer, strOutputFileName, macro_table, "创建 " + strReportType + " 表时", out strError); } // return: // -1 出错 // 0 没有创建文件(因为输出的表格为空) // 1 成功创建文件 int Create_201_report(string strLibraryCode, string strDateRange, string strCfgFile, Hashtable macro_table, string strOutputFileName, string strReportType, out string strError) { strError = ""; // macro_table["%linecount%"] = tableDepartment.Count.ToString(); macro_table["%daterange%"] = strDateRange; ReportWriter writer = null; int nRet = GetReportWriter(strCfgFile, out writer, out strError); if (nRet == -1) return -1; List<string> commands = new List<string>(); string strCommand = ""; nRet = CreateBookReportCommand( strLibraryCode, strDateRange, strReportType, // "201", "", null, out strCommand, out strError); if (nRet == -1) return -1; commands.Add(strCommand); return RunQuery( commands, writer, strOutputFileName, macro_table, "创建 " + strReportType + " 表时", out strError); } // return: // -1 出错 // 0 没有创建文件(因为输出的表格为空) // 1 成功创建文件 int Create_202_report(string strLibraryCode, string strDateRange, string strCfgFile, Hashtable macro_table, string strOutputFileName, string strReportType, out string strError) { strError = ""; // macro_table["%linecount%"] = tableDepartment.Count.ToString(); macro_table["%daterange%"] = strDateRange; ReportWriter writer = null; int nRet = GetReportWriter(strCfgFile, out writer, out strError); if (nRet == -1) return -1; List<string> commands = new List<string>(); string strCommand = ""; nRet = CreateBookReportCommand( strLibraryCode, strDateRange, strReportType, // "202", "", null, out strCommand, out strError); if (nRet == -1) return -1; commands.Add(strCommand); return RunQuery( commands, writer, strOutputFileName, macro_table, "创建 " + strReportType + " 表时", out strError); } // 212 213 // return: // -1 出错 // 0 没有创建文件(因为输出的表格为空) // 1 成功创建文件 int Create_212_report( string strLocation, string strClassType, string strClassCaption, string strDateRange, string strCfgFile, Hashtable macro_table, List<string> filters, string strOutputFileName, string strReportType, out string strError) { strError = ""; // macro_table["%linecount%"] = tableDepartment.Count.ToString(); macro_table["%daterange%"] = strDateRange; macro_table["%class%"] = string.IsNullOrEmpty(strClassCaption) == false ? strClassCaption : strClassType; ReportWriter writer = null; int nRet = GetReportWriter(strCfgFile, out writer, out strError); if (nRet == -1) return -1; List<string> commands = new List<string>(); string strCommand = ""; nRet = CreateBookReportCommand( strLocation, strDateRange, strReportType, // "212", strClassType, filters, out strCommand, out strError); if (nRet == -1) return -1; commands.Add(strCommand); return RunQuery( commands, writer, strOutputFileName, macro_table, "创建 " + strReportType + " 表时", out strError); } #if NO // return: // -1 出错 // 0 没有创建文件(因为输出的表格为空) // 1 成功创建文件 int Create_301_report( string strLocation, string strClassType, string strClassCaption, string strDateRange, string strCfgFile, Hashtable macro_table, List<string> filters, string strOutputFileName, out string strError) { strError = ""; // macro_table["%linecount%"] = tableDepartment.Count.ToString(); macro_table["%daterange%"] = strDateRange; macro_table["%class%"] = string.IsNullOrEmpty(strClassCaption) == false ? strClassCaption : strClassType; macro_table["%createtime%"] = DateTime.Now.ToLongDateString(); ReportWriter writer = null; int nRet = GetReportWriter(strCfgFile, out writer, out strError); if (nRet == -1) return -1; List<string> commands = new List<string>(); string strCommand = ""; nRet = CreateStorageReportCommand( strLocation, strDateRange, "301", strClassType, filters, out strCommand, out strError); if (nRet == -1) return -1; commands.Add(strCommand); return RunQuery( commands, writer, strOutputFileName, macro_table, out strError); } #endif // 获得存量需要的时间字符串 // 20120101-20140101 --> 00010101-20111231 static int BuildPrevDateString(string strDateRange, out string strResult, out string strError) { strError = ""; strResult = ""; string strStartDate = ""; string strEndDate = ""; try { // 将日期字符串解析为起止范围日期 // throw: // Exception DateTimeUtil.ParseDateRange(strDateRange, out strStartDate, out strEndDate); // 2014/4/11 if (string.IsNullOrEmpty(strEndDate) == true) strEndDate = strStartDate; } catch (Exception) { strError = "日期范围字符串 '" + strDateRange + "' 格式不正确"; return -1; } DateTime start = DateTimeUtil.Long8ToDateTime(strStartDate); start -= new TimeSpan(1, 0, 0, 0); // 前一天 strResult = DateTimeUtil.DateTimeToString8(new DateTime(0)) + "-" + DateTimeUtil.DateTimeToString8(start); return 0; } // return: // -1 出错 // 0 没有创建文件(因为输出的表格为空) // 1 成功创建文件 int Create_301_report( string strLocation, string strClassType, string strClassCaption, string strDateRange, string strCfgFile, Hashtable macro_table, List<string> filters, string strOutputFileName, out string strError) { strError = ""; // macro_table["%linecount%"] = tableDepartment.Count.ToString(); macro_table["%daterange%"] = strDateRange; macro_table["%class%"] = string.IsNullOrEmpty(strClassCaption) == false ? strClassCaption : strClassType; macro_table["%createtime%"] = DateTime.Now.ToLongDateString(); ReportWriter writer = null; int nRet = GetReportWriter(strCfgFile, out writer, out strError); if (nRet == -1) return -1; // 存量 string strResult = ""; // 获得存量需要的时间字符串 // 20120101-20140101 --> 00010101-20111231 nRet = BuildPrevDateString(strDateRange, out strResult, out strError); if (nRet == -1) return -1; List<string> commands = new List<string>(); string strCommand = ""; nRet = CreateStorageReportCommand( strLocation, strResult, "301", strClassType, filters, out strCommand, out strError); if (nRet == -1) return -1; commands.Add(strCommand); List<object[]> amount_table = new List<object[]>(); nRet = RunQuery( commands, ref amount_table, out strError); if (nRet == -1) return -1; // 增量 commands.Clear(); strCommand = ""; nRet = CreateStorageReportCommand( strLocation, strDateRange, "301", strClassType, filters, out strCommand, out strError); if (nRet == -1) return -1; commands.Add(strCommand); List<object[]> delta_table = new List<object[]>(); nRet = RunQuery( commands, ref delta_table, out strError); if (nRet == -1) return -1; if (delta_table.Count == 0 && amount_table.Count == 0) return 0; Table result_table = Merge301Table(amount_table, delta_table); result_table.Sort("-1:a"); macro_table["%linecount%"] = result_table.Count.ToString(); TableReader reader = new TableReader(result_table); return writer.OutputRmlReport( reader, macro_table, strOutputFileName, out strError); } static string GetString(object o) { if (o is System.DBNull) return ""; return (string)o; } static Table Merge301Table(List<object[]> amount_table, List<object[]> delta_table) { Table result_table = new Table(0); foreach (object[] line in amount_table) { string strClass = GetString(line[0]); result_table.IncValue(strClass, 0, (Int64)line[1]); // 2015/4/2 bug 0 result_table.IncValue(strClass, 2, (Int64)line[2]); // 2015/4/2 bug 0 } foreach (object[] line in delta_table) { string strClass = GetString(line[0]); result_table.IncValue(strClass, 1, (Int64)line[1]); // 2015/4/2 bug 0 result_table.IncValue(strClass, 3, (Int64)line[2]); // 2015/4/2 bug 0 } return result_table; } // return: // -1 出错 // 0 没有创建文件(因为输出的表格为空) // 1 成功创建文件 int Create_302_report( string strLocation, string strClassType, string strClassCaption, string strDateRange, string strCfgFile, Hashtable macro_table, List<string> filters, string strOutputFileName, out string strError) { strError = ""; // macro_table["%linecount%"] = tableDepartment.Count.ToString(); macro_table["%daterange%"] = strDateRange; macro_table["%class%"] = string.IsNullOrEmpty(strClassCaption) == false ? strClassCaption : strClassType; macro_table["%createtime%"] = DateTime.Now.ToLongDateString(); ReportWriter writer = null; int nRet = GetReportWriter(strCfgFile, out writer, out strError); if (nRet == -1) return -1; List<string> commands = new List<string>(); string strCommand = ""; nRet = CreateStorageReportCommand( strLocation, strDateRange, "302", strClassType, filters, out strCommand, out strError); if (nRet == -1) return -1; commands.Add(strCommand); return RunQuery( commands, writer, strOutputFileName, macro_table, "创建 302 表时", out strError); } // return: // -1 出错 // 0 没有创建文件(因为输出的表格为空) // 1 成功创建文件 int Create_4XX_report(string strLibraryCode, string strDateRange, string strCfgFile, Hashtable macro_table, string strOutputFileName, string strType, out string strError) { strError = ""; // macro_table["%linecount%"] = tableDepartment.Count.ToString(); macro_table["%daterange%"] = strDateRange; ReportWriter writer = null; int nRet = GetReportWriter(strCfgFile, out writer, out strError); if (nRet == -1) return -1; List<string> commands = new List<string>(); string strCommand = ""; // Table tableDepartment = null; nRet = CreateWorkerReportCommand( strLibraryCode, strDateRange, strType, "", out strCommand, out strError); if (nRet == -1) return -1; commands.Add(strCommand); if (strType == "472") { // Table table = new Table(0); List<object[]> table = new List<object[]>(); nRet = RunQuery( commands, ref table, out strError); if (nRet == -1) return -1; if (nRet == 0) return 0; // table.Sort("-1:a"); Table result_table = MergeCurrency(table); result_table.Sort("-1:a"); macro_table["%linecount%"] = table.Count.ToString(); TableReader reader = new TableReader(result_table); return writer.OutputRmlReport( reader, macro_table, strOutputFileName, out strError); } return RunQuery( commands, writer, strOutputFileName, macro_table, "创建 " + strType + " 表时", out strError); #if NO string strColumnSortStyle = GetColumnSortStyle(strCfgFile); if (string.IsNullOrEmpty(strColumnSortStyle) == true) { if (strType == "421") strColumnSortStyle = "4:a"; // "4:a" 操作时间 else if (strType == "422") strColumnSortStyle = "0:a"; // "0:a" 操作者 else if (strType == "431") strColumnSortStyle = "5:a"; // "5:a" 操作时间 else if (strType == "432") strColumnSortStyle = "0:a"; // "0:a" 操作者 if (strType == "441") strColumnSortStyle = "6:a"; else if (strType == "442") strColumnSortStyle = "0:a"; else if (strType == "443") strColumnSortStyle = "0:a"; } tableDepartment.Sort(SortColumnCollection.NormalToTable(strColumnSortStyle)); macro_table["%linecount%"] = tableDepartment.Count.ToString(); macro_table["%daterange%"] = strDateRange; return OutputRmlReport( tableDepartment, strCfgFile, macro_table, strOutputFileName, out strError); #endif } // return: // -1 出错 // 0 没有创建文件(因为输出的表格为空) // 1 成功创建文件 int Create_493_report( string strLibraryCode, string strClassType, string strClassCaption, string strDateRange, string strCfgFile, Hashtable macro_table, List<string> filters, string strOutputFileName, out string strError) { strError = ""; // macro_table["%linecount%"] = tableDepartment.Count.ToString(); macro_table["%daterange%"] = strDateRange; macro_table["%class%"] = string.IsNullOrEmpty(strClassCaption) == false ? strClassCaption : strClassType; macro_table["%createtime%"] = DateTime.Now.ToLongDateString(); ReportWriter writer = null; int nRet = GetReportWriter(strCfgFile, out writer, out strError); if (nRet == -1) return -1; List<string> commands = new List<string>(); string strCommand = ""; nRet = CreateClassReportCommand( strLibraryCode, strDateRange, "493", strClassType, filters, out strCommand, out strError); if (nRet == -1) return -1; commands.Add(strCommand); return RunQuery( commands, writer, strOutputFileName, macro_table, "创建 493 表时", out strError); } #if NO // source : operator unit amerce_count amerce_money undo_count undo_money expire_count total_count // target : operator amerce_count amerce_money undo_count undo_money expire_count total_count static Table MergeCurrency(Table table) { Table result_table = new Table(0); // 合并各种货币单位 // operator unit amerce_count amerce_money undo_count undo_money expire_count total_count for (int i = 0; i < table.Count; i++) { Line line = table[i]; string strKey = line.Entry; string strUnit = line.GetString(0); // unit // amerce_count result_table.IncValue(strKey, 0, line.GetInt64(1), 0); // amerce_money IncPrice(line, strUnit, 2, result_table, 1); // undo_count result_table.IncValue(strKey, 2, line.GetInt64(3), 0); // undo_money IncPrice(line, strUnit, 4, result_table, 3); // expire_count result_table.IncValue(strKey, 4, line.GetInt64(5), 0); // total_count result_table.IncValue(strKey, 5, line.GetInt64(6), 0); } return result_table; } #endif static int SOURCE_OPERATOR = 0; static int SOURCE_UNII = 1; static int SOURCE_AMERCE_COUNT = 2; static int SOURCE_AMERCE_MONEY = 3; static int SOURCE_MODIFY_COUNT = 4; static int SOURCE_MODIFY_MONEY = 5; static int SOURCE_UNDO_COUNT = 6; static int SOURCE_UNDO_MONEY = 7; static int SOURCE_EXPIRE_COUNT = 8; static int SOURCE_TOTAL_COUNT = 9; static int TARGET_AMERCE_COUNT = 0; static int TARGET_AMERCE_MONEY = 1; static int TARGET_MODIFY_COUNT = 2; static int TARGET_MODIFY_MONEY = 3; static int TARGET_UNDO_COUNT = 4; static int TARGET_UNDO_MONEY = 5; static int TARGET_EXPIRE_COUNT = 6; static int TARGET_TOTAL_COUNT = 7; // source : operator unit amerce_count amerce_money undo_count undo_money expire_count total_count // target : operator amerce_count amerce_money undo_count undo_money expire_count total_count static Table MergeCurrency(List<object[]> table) { Table result_table = new Table(0); // 合并各种货币单位 // operator unit amerce_count amerce_money undo_count undo_money expire_count total_count foreach (object[] line in table) { string strOperator = (string)line[SOURCE_OPERATOR]; string strUnit = (string)line[SOURCE_UNII]; // unit // amerce_count result_table.IncValue(strOperator, TARGET_AMERCE_COUNT, (Int64)line[SOURCE_AMERCE_COUNT]); // 2015/4/2 bug 0 // amerce_money IncPrice(line, strUnit, SOURCE_AMERCE_MONEY, result_table, TARGET_AMERCE_MONEY); // modify_count result_table.IncValue(strOperator, TARGET_MODIFY_COUNT, (Int64)line[SOURCE_MODIFY_COUNT]); // 2015/4/2 bug 0 // modify_money IncPrice(line, strUnit, SOURCE_MODIFY_MONEY, result_table, TARGET_MODIFY_MONEY); // undo_count result_table.IncValue(strOperator, TARGET_UNDO_COUNT, (Int64)line[SOURCE_UNDO_COUNT]); // 2015/4/2 bug 0 // undo_money IncPrice(line, strUnit, SOURCE_UNDO_MONEY, result_table, TARGET_UNDO_MONEY); // expire_count result_table.IncValue(strOperator, TARGET_EXPIRE_COUNT, (Int64)line[SOURCE_EXPIRE_COUNT]); // 2015/4/2 bug 0 // total_count result_table.IncValue(strOperator, TARGET_TOTAL_COUNT, (Int64)line[SOURCE_TOTAL_COUNT]); // 2015/4/2 bug 0 } return result_table; } // 将货币单位和数字拼接为一个字符串 // 注意负号应该在第一字符 static string GetCurrencyString(string strUnit, decimal value) { if (value >= 0) return strUnit + value.ToString(); return "-" + strUnit + (-value).ToString(); } static void IncPrice(object[] line, string strUnit, int source_column_index, Table result_table, int result_column_index) { object o = line[source_column_index]; if (o == null) return; if (o is System.DBNull) return; decimal value = Convert.ToDecimal(o); if (value == 0) return; if (string.IsNullOrEmpty(strUnit) == true) strUnit = "CNY"; string strNewPrice = GetCurrencyString(strUnit, value); Line result_line = result_table[(string)line[0]]; if (result_line != null) { string strExitingPrice = result_line.GetString(result_column_index); strNewPrice = PriceUtil.JoinPriceString(strExitingPrice, strNewPrice); } result_table.SetValue((string)line[0], result_column_index, strNewPrice); } #if NO static void IncPrice(Line line, string strUnit, int source_column_index, Table result_table, int result_column_index) { decimal value = line.GetDecimal(source_column_index); if (value == 0) return; if (string.IsNullOrEmpty(strUnit) == true) strUnit = "CNY"; string strNewPrice = GetCurrencyString(strUnit, value); Line result_line = result_table[line.Entry]; if (result_line != null) { string strExitingPrice = result_line.GetString(result_column_index); strNewPrice = PriceUtil.JoinPriceString(strExitingPrice, strNewPrice); } result_table.SetValue(line.Entry, result_column_index, strNewPrice); } #endif int RunQuery( List<string> commands, ref List<object[]> table, out string strError) { strError = ""; StringBuilder text = new StringBuilder(); foreach (string command in commands) { if (string.IsNullOrEmpty(command) == true) { strError = "command 不应为空"; return -1; } text.Append(command); text.Append("\r\n\r\n"); } this._connectionString = GetOperlogConnectionString(); // SQLiteUtil.GetConnectionString(Program.MainForm.UserDir, "operlog.bin"); using (SQLiteConnection connection = new SQLiteConnection(this._connectionString)) { connection.Open(); using (SQLiteCommand command = new SQLiteCommand(text.ToString(), connection)) { try { using (SQLiteDataReader dr = command.ExecuteReader(CommandBehavior.Default)) { // 如果记录不存在 if (dr == null || dr.HasRows == false) return 0; for (; ; ) { // 如果记录已经存在 while (dr.Read()) { // string strKey = GetString(dr, 0); object[] values = new object[dr.FieldCount]; dr.GetValues(values); table.Add(values); #if NO for (int i = 1; i < dr.FieldCount; i++) { } #endif } if (dr.NextResult() == false) break; } return 1; } } catch (SQLiteException ex) { strError = "执行SQL语句发生错误: " + ex.Message + "\r\nSQL 语句: " + text.ToString(); return -1; } } // end of using command } } int RunQuery( List<string> commands, ref Table table, out string strError) { strError = ""; StringBuilder text = new StringBuilder(); foreach (string command in commands) { if (string.IsNullOrEmpty(command) == true) { strError = "command 不应为空"; return -1; } text.Append(command); text.Append("\r\n\r\n"); } this._connectionString = GetOperlogConnectionString(); // SQLiteUtil.GetConnectionString(Program.MainForm.UserDir, "operlog.bin"); using (SQLiteConnection connection = new SQLiteConnection(this._connectionString)) { connection.Open(); using (SQLiteCommand command = new SQLiteCommand(text.ToString(), connection)) { try { using (SQLiteDataReader dr = command.ExecuteReader(CommandBehavior.Default)) { // 如果记录不存在 if (dr == null || dr.HasRows == false) return 0; for (; ; ) { // 如果记录已经存在 while (dr.Read()) { string strKey = GetString(dr, 0); for (int i = 1; i < dr.FieldCount; i++) { if (dr.IsDBNull(i) == true) { table.SetValue(strKey, i - 1, null); continue; } Type type = dr.GetFieldType(i); if (type.Equals(typeof(string)) == true) table.SetValue(strKey, i - 1, GetString(dr, i)); else if (type.Equals(typeof(double)) == true) table.SetValue(strKey, i - 1, GetDouble(dr, i)); else if (type.Equals(typeof(Int64)) == true) table.SetValue(strKey, i - 1, dr.GetInt64(i)); else if (type.Equals(typeof(object)) == true) table.SetValue(strKey, i - 1, dr.GetValue(i)); else table.SetValue(strKey, i - 1, dr.GetInt32(i)); } } if (dr.NextResult() == false) break; } return 1; } } catch (SQLiteException ex) { strError = "执行SQL语句发生错误: " + ex.Message + "\r\nSQL 语句: " + text.ToString(); return -1; } } // end of using command } } int RunQuery( List<string> commands, ReportWriter writer, string strOutputFileName, Hashtable macro_table, string strErrorInfoTitle, out string strError) { strError = ""; StringBuilder text = new StringBuilder(); foreach (string command in commands) { if (string.IsNullOrEmpty(command) == true) { strError = "command 不应为空"; return -1; } text.Append(command); text.Append("\r\n\r\n"); } this._connectionString = GetOperlogConnectionString(); // SQLiteUtil.GetConnectionString(Program.MainForm.UserDir, "operlog.bin"); using (SQLiteConnection connection = new SQLiteConnection(this._connectionString)) { connection.Open(); using (SQLiteCommand command = new SQLiteCommand(text.ToString(), connection)) { try { using (SQLiteDataReader dr = command.ExecuteReader(CommandBehavior.Default)) { // 如果记录不存在 if (dr == null || dr.HasRows == false) return 0; return writer.OutputRmlReport( dr, macro_table, strOutputFileName, out strError); } } catch (SQLiteException ex) { strError = strErrorInfoTitle + " 执行SQL语句发生错误: " + ex.Message + "\r\nSQL 语句: " + text.ToString(); return -1; } } // end of using command } } // 创建读者报表,关于流通业务 // 1) 按照读者自然单位分类的借书册数表 101 9101 // 2) 按照指定的单位分类的借书册数表 102 9102 // 3) 按照读者类型分类的借书册数表 111 9111 // 4) 按照读者姓名分类的借书册数表 121 9121 // 5) 没有借书的读者 122 9122 // 6) 每个读者的借阅清单 131 9131 int CreateReaderReportCommand( string strLibraryCode, string strDateRange, string strStyle, string strParameters, out string strCommand, out string strError) { strError = ""; strCommand = ""; string strStartDate = ""; string strEndDate = ""; try { // 将日期字符串解析为起止范围日期 // throw: // Exception DateTimeUtil.ParseDateRange(strDateRange, out strStartDate, out strEndDate); // 2014/3/19 if (string.IsNullOrEmpty(strEndDate) == true) strEndDate = strStartDate; } catch (Exception) { strError = "日期范围字符串 '" + strDateRange + "' 格式不正确"; return -1; } if (StringUtil.IsInList("101", strStyle) == true) { // 101 表 按照读者 *自然单位* 分类的借书册数表 #if NO strCommand = "select reader.department, count(*) as count " + " FROM operlogcircu left outer JOIN reader ON operlogcircu.readerbarcode <> '' AND operlogcircu.readerbarcode = reader.readerbarcode " + " WHERE operlogcircu.operation = 'borrow' and operlogcircu.action = 'borrow' " + " AND operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND reader.librarycode = '" + strLibraryCode + "' " + " GROUP BY reader.department ORDER BY count DESC, reader.department;"; #endif // 2015/6/17 增加了 return 列 strCommand = "select reader.department, " + " count(case operlogcircu.operation when 'borrow' then operlogcircu.action end) as borrow, " + " count(case operlogcircu.operation when 'return' then operlogcircu.action end) as return " + " FROM operlogcircu left outer JOIN reader ON operlogcircu.readerbarcode <> '' AND operlogcircu.readerbarcode = reader.readerbarcode " + " WHERE operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND reader.librarycode = '" + strLibraryCode + "' " + " GROUP BY reader.department ORDER BY borrow DESC, reader.department;"; } else if (StringUtil.IsInList("9101", strStyle) == true) { // 9101 表 按照读者 *自然单位* 分类的阅读册数表 strCommand = "select reader.department, " + " count(*) as count1 " + " FROM operlogcircu left outer JOIN reader ON operlogcircu.readerbarcode <> '' AND operlogcircu.readerbarcode = reader.readerbarcode " + " WHERE operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND operlogcircu.operation = 'return' AND operlogcircu.action = 'read' " + " AND reader.librarycode = '" + strLibraryCode + "' " + " GROUP BY reader.department ORDER BY count1 DESC, reader.department;"; } else if (StringUtil.IsInList("102", strStyle) == true) { // 102 表 按照 *指定的单位* 分类的借书册数表 // 这里每次只能获得一个单位的一行数据。需要按照不同单位 (strParameters) 多次循环调用本函数 #if NO strCommand = "select '" + strParameters + "' as department, count(*) as count " + " FROM operlogcircu JOIN reader ON operlogcircu.readerbarcode <> '' AND operlogcircu.readerbarcode = reader.readerbarcode " + " WHERE operlogcircu.operation = 'borrow' and operlogcircu.action = 'borrow' " + " AND operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND reader.librarycode = '" + strLibraryCode + "' AND reader.department like '" + strParameters + "' " + " ORDER BY count DESC, department;"; #endif // 2015/6/17 增加了 return 列 strCommand = "select '" + strParameters + "' as department, " + " count(case operlogcircu.operation when 'borrow' then operlogcircu.action end) as borrow, " + " count(case operlogcircu.operation when 'return' then operlogcircu.action end) as return " + " FROM operlogcircu JOIN reader ON operlogcircu.readerbarcode <> '' AND operlogcircu.readerbarcode = reader.readerbarcode " + " WHERE operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND reader.librarycode = '" + strLibraryCode + "' AND reader.department like '" + strParameters + "' " + " ORDER BY borrow DESC, department;"; } else if (StringUtil.IsInList("9102", strStyle) == true) { // 9102 表 按照 *指定的单位* 分类的阅读册数表 // 这里每次只能获得一个单位的一行数据。需要按照不同单位 (strParameters) 多次循环调用本函数 strCommand = "select '" + strParameters + "' as department, " + " count(*) as count1 " + " FROM operlogcircu JOIN reader ON operlogcircu.readerbarcode <> '' AND operlogcircu.readerbarcode = reader.readerbarcode " + " WHERE operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND operlogcircu.operation = 'return' AND operlogcircu.action = 'read' " + " AND reader.librarycode = '" + strLibraryCode + "' AND reader.department like '" + strParameters + "' " + " ORDER BY count1 DESC, department;"; } else if (StringUtil.IsInList("111", strStyle) == true) { // 111 表 按照读者 *自然类型* 分类的借书册数表 #if NO strCommand = "select reader.readertype, count(*) as count " + " FROM operlogcircu JOIN reader ON operlogcircu.readerbarcode <> '' AND operlogcircu.readerbarcode = reader.readerbarcode " + " WHERE operlogcircu.operation = 'borrow' and operlogcircu.action = 'borrow' " + " AND operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND reader.librarycode = '" + strLibraryCode + "' " + " GROUP BY reader.readertype ORDER BY count DESC, reader.readertype;"; #endif // 2015/6/17 增加了 return 列 strCommand = "select reader.readertype, " + " count(case operlogcircu.operation when 'borrow' then operlogcircu.action end) as borrow, " + " count(case operlogcircu.operation when 'return' then operlogcircu.action end) as return " + " FROM operlogcircu JOIN reader ON operlogcircu.readerbarcode <> '' AND operlogcircu.readerbarcode = reader.readerbarcode " + " WHERE operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND reader.librarycode = '" + strLibraryCode + "' " + " GROUP BY reader.readertype ORDER BY borrow DESC, reader.readertype;"; } else if (StringUtil.IsInList("9111", strStyle) == true) { // 9111 表 按照读者 *自然类型* 分类的阅读册数表 strCommand = "select reader.readertype, " + " count(*) as count1 " + " FROM operlogcircu JOIN reader ON operlogcircu.readerbarcode <> '' AND operlogcircu.readerbarcode = reader.readerbarcode " + " WHERE operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND operlogcircu.operation = 'return' AND operlogcircu.action = 'read' " + " AND reader.librarycode = '" + strLibraryCode + "' " + " GROUP BY reader.readertype ORDER BY count1 DESC, reader.readertype;"; } else if (StringUtil.IsInList("121", strStyle) == true) { // 121 表 按照读者 *姓名* 分类的借书册数表 #if NO strCommand = "select operlogcircu.readerbarcode, reader.name, reader.department, count(*) as count " + " FROM operlogcircu JOIN reader ON operlogcircu.readerbarcode <> '' AND operlogcircu.readerbarcode = reader.readerbarcode " + " WHERE operlogcircu.operation = 'borrow' and operlogcircu.action = 'borrow' " + " AND operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND reader.librarycode = '" + strLibraryCode + "' " + " GROUP BY operlogcircu.readerbarcode ORDER BY count DESC, reader.department, operlogcircu.readerbarcode ;"; #endif // 2015/6/17 增加了 return 列 strCommand = "select operlogcircu.readerbarcode, reader.name, reader.department, " + " count(case operlogcircu.operation when 'borrow' then operlogcircu.action end) as borrow, " + " count(case operlogcircu.operation when 'return' then operlogcircu.action end) as return " + " FROM operlogcircu JOIN reader ON operlogcircu.readerbarcode <> '' AND operlogcircu.readerbarcode = reader.readerbarcode " + " WHERE operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND reader.librarycode = '" + strLibraryCode + "' " + " GROUP BY operlogcircu.readerbarcode ORDER BY borrow DESC, reader.department, operlogcircu.readerbarcode ;"; } else if (StringUtil.IsInList("9121", strStyle) == true) { // 9121 表 按照读者 *姓名* 分类的阅读册数表 strCommand = "select operlogcircu.readerbarcode, reader.name, reader.department, " + " count(*) as count1 " + " FROM operlogcircu JOIN reader ON operlogcircu.readerbarcode <> '' AND operlogcircu.readerbarcode = reader.readerbarcode " + " WHERE operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND operlogcircu.operation = 'return' AND operlogcircu.action = 'read' " + " AND reader.librarycode = '" + strLibraryCode + "' " + " GROUP BY operlogcircu.readerbarcode ORDER BY count1 DESC, reader.department, operlogcircu.readerbarcode ;"; } else if (StringUtil.IsInList("122", strStyle) == true) { /* create temp table tt as select operlogcircu.readerbarcode as tt FROM operlogcircu JOIN reader ON operlogcircu.readerbarcode <> '' AND operlogcircu.readerbarcode = reader.readerbarcode WHERE operlogcircu.operation = 'borrow' and operlogcircu.action = 'borrow' AND operlogcircu.date >= '20120101' AND operlogcircu.date <= '20121201' AND reader.librarycode = '合肥望湖小学' ; select readerbarcode, name, department from reader WHERE librarycode = '合肥望湖小学' AND readerbarcode not in tt AND (select count(*) from tt) > 0 ORDER BY department, readerbarcode ; * */ // 122 表 按照读者 *姓名* 没有借书的读者 strCommand = "create temp table tt as select operlogcircu.readerbarcode " + " FROM operlogcircu JOIN reader ON operlogcircu.readerbarcode <> '' AND operlogcircu.readerbarcode = reader.readerbarcode AND reader.state = '' " // 2016/11/24 增加对 state 字段的判断 + " WHERE operlogcircu.operation = 'borrow' and operlogcircu.action = 'borrow' " + " AND operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND reader.librarycode = '" + strLibraryCode + "';" + " select readerbarcode, name, department from reader " + " WHERE (select count(*) from tt) > 0 " + " AND librarycode = '" + strLibraryCode + "' " + " AND readerbarcode not in tt " + " AND state = '' " // 状态值为空的读者才能参与此项统计 + " ORDER BY department, readerbarcode ;"; // nNumber = 122; } else if (StringUtil.IsInList("9122", strStyle) == true) { // 9122 表 按照读者 *姓名* 没有阅读的读者 strCommand = "create temp table tt as select operlogcircu.readerbarcode " + " FROM operlogcircu JOIN reader ON operlogcircu.readerbarcode <> '' AND operlogcircu.readerbarcode = reader.readerbarcode AND reader.state = '' " // 2016/11/24 增加对 state 字段的判断 + " WHERE operlogcircu.operation = 'return' and operlogcircu.action = 'read' " + " AND operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND reader.librarycode = '" + strLibraryCode + "';" + " select readerbarcode, name, department from reader " + " WHERE (select count(*) from tt) > 0 " + " AND librarycode = '" + strLibraryCode + "' " + " AND readerbarcode not in tt " + " AND state = '' " // 状态值为空的读者才能参与此项统计 + " ORDER BY department, readerbarcode ;"; } else if (StringUtil.IsInList("131", strStyle) == true) { // 131 表 每个读者的借阅清单 strCommand = "select oper1.itembarcode, biblio.summary, oper1.opertime as 'borrowtime', oper2.opertime as 'returntime' from operlogcircu as oper1 " + " left join operlogcircu as oper2 on oper2.itembarcode <> '' AND oper1.itembarcode = oper2.itembarcode and oper2.readerbarcode <> '' AND oper1.readerbarcode = oper2.readerbarcode and oper2.operation = 'return' and oper1.opertime <= oper2.opertime " + " left JOIN item ON oper1.itembarcode <> '' AND oper1.itembarcode = item.itembarcode " + " left JOIN biblio ON item.bibliorecpath <> '' AND biblio.bibliorecpath = item.bibliorecpath " + " where oper1.operation = 'borrow' and oper1.action = 'borrow' " + " AND oper1.date >= '" + strStartDate + "' AND oper1.date <= '" + strEndDate + "' " + " AND oper1.readerbarcode = '" + strParameters + "' " + " group by oper1.readerbarcode, oper1.itembarcode, oper1.opertime order by oper1.readerbarcode, oper1.opertime ; "; } else if (StringUtil.IsInList("9131", strStyle) == true) { // 9131 表 每个读者的阅读清单 strCommand = "select oper1.itembarcode, biblio.summary, oper1.opertime as 'readtime' from operlogcircu as oper1 " + " left JOIN item ON oper1.itembarcode <> '' AND oper1.itembarcode = item.itembarcode " + " left JOIN biblio ON item.bibliorecpath <> '' AND biblio.bibliorecpath = item.bibliorecpath " + " where oper1.operation = 'return' and oper1.action = 'read' " + " AND oper1.date >= '" + strStartDate + "' AND oper1.date <= '" + strEndDate + "' " + " AND oper1.readerbarcode = '" + strParameters + "' " + " group by oper1.readerbarcode, oper1.itembarcode, oper1.opertime order by oper1.readerbarcode, oper1.opertime ; "; } else if (StringUtil.IsInList("141", strStyle) == true) { DateTime now = DateTimeUtil.Long8ToDateTime(strEndDate); now = new DateTime(now.Year, now.Month, now.Day, 12, 0, 0, 0); string strToday = now.ToString("s"); // 141 表 超期读者清单 strCommand = "select item.borrower, reader.name, reader.department, item.itembarcode, biblio.summary, item.borrowtime, item.borrowperiod, item.returningtime " + " from item " + " left JOIN reader ON item.borrower <> '' AND item.borrower = reader.readerbarcode " + " left JOIN biblio ON item.bibliorecpath <> '' AND biblio.bibliorecpath = item.bibliorecpath " + " where item.borrowtime <> '' " + " AND item.returningtime < '" + strToday + "' " + " AND reader.librarycode = '" + strLibraryCode + "' " + " order by reader.department, item.borrower, item.returningtime ; "; } else { strError = "无法支持的 strStyle '" + strStyle + "'"; return -1; } return 0; } static string GetString(SQLiteDataReader dr, int index) { if (dr.IsDBNull(index) == true) return ""; else return dr.GetString(index); } static double GetDouble(SQLiteDataReader dr, int index) { if (dr.IsDBNull(index) == true) return 0; else return dr.GetDouble(index); } // 创建图书报表,关于流通业务 // 1) 201 9201 按照图书种分类的借书册数表 // 2) 202 9202 从来没有借出的图书 *种* 。册数列表示种下属的册数,不是被借出的册数 // 4) 212 9212 按照图书 *分类* 分类的借书册数表 int CreateBookReportCommand( string strLocation, // "名称/" string strDateRange, string strStyle, string strParameters, List<string> filters, out string strCommand, out string strError) { strError = ""; strCommand = ""; string strStartDate = ""; string strEndDate = ""; try { // 将日期字符串解析为起止范围日期 // throw: // Exception DateTimeUtil.ParseDateRange(strDateRange, out strStartDate, out strEndDate); // 2014/4/11 if (string.IsNullOrEmpty(strEndDate) == true) strEndDate = strStartDate; } catch (Exception) { strError = "日期范围字符串 '" + strDateRange + "' 格式不正确"; return -1; } string strLibraryCode = Global.GetLibraryCode(strLocation); // string strLocationLike = " operlogcircu.librarycode like '%," + strLibraryCode + ",%' "; // 不知何时用的这种方法。这种方法的问题是,如果一些图书中途被划拨给某个其他分馆,用这种方式就会导致 [全部] 的几个表统计出来的数量偏少。而用 item.location 判断就没有这个问题 string strLocationLike = " item.location like '" + strLocation + "%' "; // 2017/6/21 改回用这种方式。因为要统计洞庭湖校区的 2017 2 到 6 月的数据 if (string.IsNullOrEmpty(Global.GetLocationRoom(strLocation)) == false) { // 改为沿用以前的方法 strLocationLike = " item.location like '" + strLocation + "%' "; if (string.IsNullOrEmpty(strLocation) == true) strLocationLike = " item.location = '' "; // 2014/5/28 else if (strLocation == "/") strLocationLike = " (item.location like '/%' OR item.location not like '%/%') "; // 全局的馆藏点比较特殊 } // 通过 item 表实现的地点筛选 string strLocationLike_item = " item.location like '" + strLocation + "%' "; if (string.IsNullOrEmpty(strLocation) == true) strLocationLike_item = " item.location = '' "; else if (strLocation == "/") strLocationLike_item = " (item.location like '/%' OR item.location not like '%/%') "; // 全局的馆藏点比较特殊 #if NO string strLocationLike = " item.location like '" + strLocation + "%' "; if (string.IsNullOrEmpty(strLocation) == true) strLocationLike = " item.location = '' "; // 2014/5/28 else if (strLocation == "/") strLocationLike = " (item.location like '/%' OR item.location not like '%/%') "; // 全局的馆藏点比较特殊 #endif if (StringUtil.IsInList("201", strStyle) == true) { // 201 表 按照图书 *种* 分类的借书册数表 #if NO strCommand = "select item.bibliorecpath, biblio.summary, count(*) as count " + " FROM operlogcircu " + " JOIN item ON operlogcircu.itembarcode <> '' AND operlogcircu.itembarcode = item.itembarcode " + " JOIN biblio ON item.bibliorecpath <> '' AND biblio.bibliorecpath = item.bibliorecpath " + " WHERE operlogcircu.operation = 'borrow' and operlogcircu.action = 'borrow' " + " AND operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND " + strLocationLike + " GROUP BY item.bibliorecpath ORDER BY count DESC ;"; #endif // 2015/6/17 增加了 return 列 strCommand = "select item.bibliorecpath, biblio.summary, " + " count(case operlogcircu.operation when 'borrow' then operlogcircu.action end) as borrow, " + " count(case operlogcircu.operation when 'return' then operlogcircu.action end) as return " + " FROM operlogcircu " + " left JOIN item ON operlogcircu.itembarcode <> '' AND operlogcircu.itembarcode = item.itembarcode " + " left JOIN biblio ON item.bibliorecpath <> '' AND biblio.bibliorecpath = item.bibliorecpath " + " WHERE operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND " + strLocationLike + " GROUP BY item.bibliorecpath ORDER BY borrow DESC ;"; } else if (StringUtil.IsInList("9201", strStyle) == true) { // 9201 表 按照图书 *种* 分类的阅读册数表 strCommand = "select item.bibliorecpath, biblio.summary, " + " count(*) as count1 " + " FROM operlogcircu " + " left JOIN item ON operlogcircu.itembarcode <> '' AND operlogcircu.itembarcode = item.itembarcode " + " left JOIN biblio ON item.bibliorecpath <> '' AND biblio.bibliorecpath = item.bibliorecpath " + " WHERE operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND operlogcircu.operation = 'return' AND operlogcircu.action = 'read' " + " AND " + strLocationLike + " GROUP BY item.bibliorecpath ORDER BY count1 DESC ;"; } else if (StringUtil.IsInList("202", strStyle) == true) { // 202 表 从来没有借出的图书 *种* 。册数列表示种下属的册数,不是被借出的册数 strCommand = "select item.bibliorecpath, biblio.summary, count(*) as count " + " FROM item " + " left JOIN biblio ON item.bibliorecpath <> '' AND biblio.bibliorecpath = item.bibliorecpath " + " WHERE item.bibliorecpath not in " + " ( select item.bibliorecpath " + " FROM operlogcircu JOIN item ON operlogcircu.itembarcode <> '' AND operlogcircu.itembarcode = item.itembarcode " + " WHERE operlogcircu.operation = 'borrow' and operlogcircu.action = 'borrow' " + " AND operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND " + strLocationLike + " ) " + " AND " + strLocationLike_item // 限定 item 表里面的记录范围为分馆的册 + " AND substr(item.createtime,1,10) <= '" + strEndDate.Insert(6, "-").Insert(4, "-") + "' " // 限定册记录创建的时间在 end 以前 + " GROUP BY item.bibliorecpath ORDER BY item.bibliorecpath;"; } else if (StringUtil.IsInList("9202", strStyle) == true) { // 9202 表 从来没有阅读的图书 *种* 。册数列表示种下属的册数,不是被阅读的册数 strCommand = "select item.bibliorecpath, biblio.summary, count(*) as count " + " FROM item " + " left JOIN biblio ON item.bibliorecpath <> '' AND biblio.bibliorecpath = item.bibliorecpath " + " WHERE item.bibliorecpath not in " + " ( select item.bibliorecpath " + " FROM operlogcircu JOIN item ON operlogcircu.itembarcode <> '' AND operlogcircu.itembarcode = item.itembarcode " + " WHERE operlogcircu.operation = 'return' and operlogcircu.action = 'read' " + " AND operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND " + strLocationLike + " ) " + " AND " + strLocationLike_item // 限定 item 表里面的记录范围为分馆的册 + " AND substr(item.createtime,1,10) <= '" + strEndDate.Insert(6, "-").Insert(4, "-") + "' " // 限定册记录创建的时间在 end 以前 + " GROUP BY item.bibliorecpath ORDER BY item.bibliorecpath;"; } else if (StringUtil.IsInList("212", strStyle) == true || StringUtil.IsInList("213", strStyle) == true) { #if NO string strOperation = "borrow"; if (StringUtil.IsInList("213", strStyle) == true) strOperation = "return"; #endif string strClassTableName = "class_" + strParameters; int nRet = PrepareDistinctClassTable( strClassTableName, out strError); if (nRet == -1) return -1; string strDistinctClassTableName = "class_" + strParameters + "_d"; string strClassColumn = BuildClassColumnFragment(strDistinctClassTableName, filters, "other"); #if NO // 去掉重复的 bibliorecpath 条目 string strSubSelect = " ( select * from " + strClassTableName + " group by bibliorecpath) a "; #endif // 212 表 按照图书 *分类* 分类的借书册数表 #if NO // 213 表 按照图书 *分类* 分类的还书册数表 strCommand = // "select substr(" + strDistinctClassTableName + ".class,1,1) as classhead, count(*) as count " "select " + strClassColumn + " as classhead, count(*) as count " // strCommand = "select " + strClassTableName + ".class as class, count(*) as count " + " FROM operlogcircu left outer JOIN item ON operlogcircu.itembarcode <> '' AND operlogcircu.itembarcode = item.itembarcode " + " left outer JOIN " + strDistinctClassTableName + " ON item.bibliorecpath <> '' AND " + strDistinctClassTableName + ".bibliorecpath = item.bibliorecpath " + " WHERE operlogcircu.operation = '" + strOperation + "' " // and operlogcircu.action = 'borrow' + " AND operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND " + strLocationLike + " GROUP BY classhead ORDER BY classhead ;"; #endif // 2015/6/17 212 和 213 表合并为 212 表 strCommand = // "select substr(" + strDistinctClassTableName + ".class,1,1) as classhead, count(*) as count " "select " + strClassColumn + " as classhead, " + " count(case operlogcircu.operation when 'borrow' then operlogcircu.action end) as borrow, " + " count(case operlogcircu.operation when 'return' then operlogcircu.action end) as return " // strCommand = "select " + strClassTableName + ".class as class, count(*) as count " + " FROM operlogcircu left outer JOIN item ON operlogcircu.itembarcode <> '' AND operlogcircu.itembarcode = item.itembarcode " + " left outer JOIN " + strDistinctClassTableName + " ON item.bibliorecpath <> '' AND " + strDistinctClassTableName + ".bibliorecpath = item.bibliorecpath " + " WHERE operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND " + strLocationLike + " GROUP BY classhead ORDER BY classhead ;"; } else if (StringUtil.IsInList("9212", strStyle) == true || StringUtil.IsInList("9213", strStyle) == true) { string strClassTableName = "class_" + strParameters; int nRet = PrepareDistinctClassTable( strClassTableName, out strError); if (nRet == -1) return -1; string strDistinctClassTableName = "class_" + strParameters + "_d"; string strClassColumn = BuildClassColumnFragment(strDistinctClassTableName, filters, "other"); // 9212 表 按照图书 *分类* 分类的借书册数表 strCommand = "select " + strClassColumn + " as classhead, " + " count(*) as count1 " + " FROM operlogcircu left outer JOIN item ON operlogcircu.itembarcode <> '' AND operlogcircu.itembarcode = item.itembarcode " + " left outer JOIN " + strDistinctClassTableName + " ON item.bibliorecpath <> '' AND " + strDistinctClassTableName + ".bibliorecpath = item.bibliorecpath " + " WHERE operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND operlogcircu.operation = 'return' AND operlogcircu.action = 'read' " + " AND " + strLocationLike + " GROUP BY classhead ORDER BY classhead ;"; } else { strError = "不支持的 strStyle '" + strStyle + "'"; return -1; } return 0; } // filters 中不允许空字符串 static string BuildClassColumnFragment(string strClassTableName, List<string> filters, string strStyle) { if (filters == null || filters.Count == 0) return "substr(" + strClassTableName + ".class,1,1)"; StringBuilder text = new StringBuilder(); text.Append("( case "); foreach (string filter in filters) { text.Append(" when " + strClassTableName + ".class like '" + filter + "%' then '" + filter + "' "); } if (strStyle == "rest1") text.Append(" else substr(" + strClassTableName + ".class,1,1) "); else if (strStyle == "other") text.Append(" else '其它' "); text.Append(" end )"); return text.ToString(); } // 创建图书报表,关于典藏业务 // 1) 301 按照馆藏地点的当前全部 图书分类 种册统计 // 2) 302 在架情况(是否被借出) int CreateStorageReportCommand( string strLocation, // "名称/" string strDateRange, string strStyle, string strClassType, List<string> filters, out string strCommand, out string strError) { strError = ""; strCommand = ""; string strStartDate = ""; string strEndDate = ""; try { // 将日期字符串解析为起止范围日期 // throw: // Exception DateTimeUtil.ParseDateRange(strDateRange, out strStartDate, out strEndDate); // 2014/4/11 if (string.IsNullOrEmpty(strEndDate) == true) strEndDate = strStartDate; } catch (Exception) { strError = "日期范围字符串 '" + strDateRange + "' 格式不正确"; return -1; } string strLocationLike = " item.location like '" + strLocation + "%' "; if (string.IsNullOrEmpty(strLocation) == true) strLocationLike = " item.location = '' "; // 2014/5/28 else if (strLocation == "/") strLocationLike = " (item.location like '/%' OR item.location not like '%/%') "; // 全局的馆藏点比较特殊 if (StringUtil.IsInList("301", strStyle) == true) { /* select class1, count(path1) as bcount, sum (icount) from ( select substr(class_clc.class,1,1) as class1, item.bibliorecpath as path1, count(item.itemrecpath) as icount FROM item JOIN class_clc ON class_clc.bibliorecpath = item.bibliorecpath WHERE item.location like '合肥望湖小学/%' group by path1 ) group by class1 * * */ string strClassTableName = "class_" + strClassType; int nRet = PrepareDistinctClassTable( strClassTableName, out strError); if (nRet == -1) return -1; string strDistinctClassTableName = "class_" + strClassType + "_d"; string strClassColumn = BuildClassColumnFragment(strDistinctClassTableName, filters, "other"); strStartDate = strStartDate.Insert(6, "-").Insert(4, "-"); strEndDate = strEndDate.Insert(6, "-").Insert(4, "-"); string strTimeCondition = " substr(item.createtime,1,10) >= '" + strStartDate + "' " // 限定册记录创建的时间在 start 以后 + " AND substr(item.createtime,1,10) <= '" + strEndDate + "' "; if (strStartDate.Replace("-", "") == "00010101") strTimeCondition = " ((substr(item.createtime,1,10) >= '" + strStartDate + "' " // 限定册记录创建的时间在 start 以后 + " AND substr(item.createtime,1,10) <= '" + strEndDate + "' )" + " OR item.createtime = '') "; // 301 表 按照图书 *分类* 分类的图书册数表 strCommand = "select classhead, count(path1) as bcount, sum (icount) from ( " // + "select substr(" + strDistinctClassTableName + ".class,1,1) as classhead, item.bibliorecpath as path1, count(item.itemrecpath) as icount " + "select " + strClassColumn + " as classhead, item.bibliorecpath as path1, count(item.itemrecpath) as icount " + " FROM item " + " LEFT OUTER JOIN " + strDistinctClassTableName + " ON item.bibliorecpath <> '' AND " + strDistinctClassTableName + ".bibliorecpath = item.bibliorecpath " + " WHERE " + strLocationLike //+ " AND substr(item.createtime,1,10) >= '" + strStartDate + "' " // 限定册记录创建的时间在 start 以后 //+ " AND substr(item.createtime,1,10) <= '" + strEndDate + "' " // 限定册记录创建的时间在 end 以前 + " AND " + strTimeCondition + " GROUP BY path1 " + " ) group by classhead ORDER BY classhead ;"; // left outer join 是包含了左边找不到右边的那些行, 然后 class 列为 NULL } else if (StringUtil.IsInList("302", strStyle) == true) { /* select substr(class_clc.class,1,1) as class1, count(case when item.borrower <> '' then item.borrower end) as outitems, count(case when item.borrower = '' then item.borrower end) as initems, count(item.itemrecpath) as icount, printf("%.2f%", 100.0 * count(case when item.borrower <> '' then item.borrower end) / count(item.itemrecpath)) as percent FROM item JOIN class_clc ON class_clc.bibliorecpath = item.bibliorecpath WHERE item.location like '合肥望湖小学/%' group by class1 * * */ string strClassTableName = "class_" + strClassType; int nRet = PrepareDistinctClassTable( strClassTableName, out strError); if (nRet == -1) return -1; string strDistinctClassTableName = "class_" + strClassType + "_d"; string strClassColumn = BuildClassColumnFragment(strDistinctClassTableName, filters, "other"); strEndDate = strEndDate.Insert(6, "-").Insert(4, "-"); // 302 表 册在架情况 strCommand = // "select substr(" + strDistinctClassTableName + ".class,1,1) as classhead, " "select " + strClassColumn + " as classhead, " + " count(case when item.borrower <> '' then item.borrower end) as outitems, " + " count(case when item.borrower = '' then item.borrower end) as initems, " + " count(item.itemrecpath) as icount " // + " printf(\"%.2f%\", 100.0 * count(case when item.borrower <> '' then item.borrower end) / count(item.itemrecpath)) as percent " + " FROM item " + " LEFT OUTER JOIN " + strDistinctClassTableName + " ON item.bibliorecpath <> '' AND " + strDistinctClassTableName + ".bibliorecpath = item.bibliorecpath " + " WHERE " + strLocationLike + " AND substr(item.createtime,1,10) <= '" + strEndDate + "' " // 限定册记录创建的时间在 end 以前 + " GROUP BY classhead ORDER BY classhead ;"; // left outer join 是包含了左边找不到右边的那些行, 然后 class 列为 NULL } else { strError = "不支持的 strStyle '" + strStyle + "'"; return -1; } return 0; } // 获得一个分馆内读者记录的所有单位名称 public int GetAllReaderDepartments( string strLibraryCode, out List<string> results, out string strError) { strError = ""; results = new List<string>(); string strCommand = "select department, count(*) as count " + " FROM reader " + " WHERE librarycode = '" + strLibraryCode + "' " + " GROUP BY department ;"; this._connectionString = GetOperlogConnectionString(); // SQLiteUtil.GetConnectionString(Program.MainForm.UserDir, "operlog.bin"); using (SQLiteConnection connection = new SQLiteConnection(this._connectionString)) { connection.Open(); using (SQLiteCommand command = new SQLiteCommand(strCommand, connection)) { try { SQLiteDataReader dr = command.ExecuteReader(CommandBehavior.SingleResult); try { // 如果记录不存在 if (dr == null || dr.HasRows == false) return 0; // 如果记录已经存在 while (dr.Read()) { results.Add(dr.GetString(0)); } } finally { dr.Close(); } } catch (SQLiteException ex) { strError = "执行SQL语句发生错误: " + ex.Message + "\r\nSQL 语句: " + strCommand; return -1; } } // end of using command } return 0; } // 获得一个分馆内册记录的所有馆藏地点名称 // parameters: // bRoot 是否包含分馆这个名称。如果 == true,表示要包含,在 results 中会返回一个这样的 "望湖小学/" public int GetAllItemLocations( string strLibraryCode, bool bRoot, out List<string> results, out string strError) { strError = ""; results = new List<string>(); string strLibraryCodeFilter = ""; if (string.IsNullOrEmpty(strLibraryCode) == true) { strLibraryCodeFilter = "(location like '/%' OR location not like '%/%') "; } else { strLibraryCodeFilter = "location like '" + strLibraryCode + "/%' "; } string strCommand = "select location, count(*) as count " + " FROM item " + " WHERE " + strLibraryCodeFilter + " " + " GROUP BY location ;"; this._connectionString = GetOperlogConnectionString(); // SQLiteUtil.GetConnectionString(Program.MainForm.UserDir, "operlog.bin"); using (SQLiteConnection connection = new SQLiteConnection(this._connectionString)) { connection.Open(); using (SQLiteCommand command = new SQLiteCommand(strCommand, connection)) { try { SQLiteDataReader dr = command.ExecuteReader(CommandBehavior.SingleResult); try { // 如果记录不存在 if (dr == null || dr.HasRows == false) goto END1; // 如果记录已经存在 while (dr.Read()) { results.Add(RemoveShelfName(dr.GetString(0))); } } finally { dr.Close(); } } catch (SQLiteException ex) { strError = "执行 SQL 语句发生错误: " + ex.Message + "\r\nSQL 语句: " + strCommand; return -1; } } // end of using command } END1: // 去重 StringUtil.RemoveDupNoSort(ref results); if (bRoot == true) { string strRoot = strLibraryCode + "/"; if (results.IndexOf(strRoot) == -1) results.Insert(0, strRoot); } return 0; } // 2016/6/4 // 去掉末尾的 -架号 部分 static string RemoveShelfName(string strText) { int index = strText.LastIndexOfAny(new char[] { '/', '-' }); if (index == -1) return strText; if (strText[index] == '/') return strText; return strText.Substring(0, index); } // 获得一个分馆内读者记录的证条码号、姓名和单位名称 public int GetAllReaderDepartments( string strLibraryCode, ref Table table, out string strError) { strError = ""; if (table == null) table = new Table(2); string strCommand = "select readerbarcode, name, department " + " FROM reader " + " WHERE librarycode = '" + strLibraryCode + "' " + " ORDER BY department ;"; this._connectionString = GetOperlogConnectionString(); // SQLiteUtil.GetConnectionString(Program.MainForm.UserDir, "operlog.bin"); using (SQLiteConnection connection = new SQLiteConnection(this._connectionString)) { connection.Open(); using (SQLiteCommand command = new SQLiteCommand(strCommand, connection)) { try { SQLiteDataReader dr = command.ExecuteReader(CommandBehavior.SingleResult); try { // 如果记录不存在 if (dr == null || dr.HasRows == false) return 0; // 如果记录已经存在 while (dr.Read()) { string strKey = GetString(dr, 0); // 证条码号 姓名 table.SetValue(strKey, 0, GetString(dr, 1)); // 单位 table.SetValue(strKey, 1, GetString(dr, 2)); } } finally { dr.Close(); } } catch (SQLiteException ex) { strError = "执行SQL语句发生错误: " + ex.Message + "\r\nSQL 语句: " + strCommand; return -1; } } // end of using command } return 0; } // 从一个逗号间隔的字符串中析出 3 位数字 static int GetStyleNumber(string strStyle) { string[] parts = strStyle.Split(new char[] { ',' }); foreach (string s in parts) { if (s.Length == 3 && StringUtil.IsPureNumber(s) == true) { Int32 v = 0; Int32.TryParse(s, out v); return v; } } return 0; } // 创建业务操作报表,关于采购\编目\典藏\流通\期刊\读者管理业务 // 1) 订购流水 411 // 2) 订购工作量 按工作人员 412 // 1) 编目流水 421 // 2) 编目工作量 按工作人员 422 // 1) 册登记流水 431 // 2) 册登记工作量 按工作人员 432 // 1) 出纳流水 441 // 2) 出纳工作量 按工作人员 442 // 2) 出纳工作量 按馆藏地点 443 // 1) 期登记流水 451 // 2) 期登记工作量 按工作人员 452 // 1) 违约金流水 471 // 2) 违约金工作量 按工作人员 472 // 1) 入馆登记流水 481 // 2) 入馆登记工作量 按门名称 482 // 1) 获取对象流水 491 // 2) 获取对象工作量 按操作者 492 int CreateWorkerReportCommand( string strLibraryCode, string strDateRange, string strStyle, string strParameters, out string strCommand, out string strError) { strError = ""; strCommand = ""; string strStartDate = ""; string strEndDate = ""; try { // 将日期字符串解析为起止范围日期 // throw: // Exception DateTimeUtil.ParseDateRange(strDateRange, out strStartDate, out strEndDate); if (string.IsNullOrEmpty(strEndDate) == true) strEndDate = strStartDate; } catch (Exception) { strError = "日期范围字符串 '" + strDateRange + "' 格式不正确"; return -1; } int nNumber = GetStyleNumber(strStyle); if (nNumber == 421) { // 421 表,编目流水 strCommand = "select '', operlogbiblio.action, operlogbiblio.bibliorecpath, biblio.summary, operlogbiblio.opertime, operlogbiblio.operator " // + " FROM operlogbiblio " + " left outer JOIN biblio ON operlogbiblio.bibliorecpath <> '' AND operlogbiblio.bibliorecpath = biblio.bibliorecpath " + " left outer JOIN user ON operlogbiblio.operator <> '' AND operlogbiblio.operator = user.id " + " WHERE " + " operlogbiblio.date >= '" + strStartDate + "' AND operlogbiblio.date <= '" + strEndDate + "' " + " AND user.librarycodelist like '%," + strLibraryCode + ",%' " + " ORDER BY operlogbiblio.opertime ;"; } else if (nNumber == 422) { // 422 表,每个工作人员编目各类工作量 strCommand = "select operlogbiblio.operator, " // + " count(case operlogbiblio.action when 'new' then operlogbiblio.action end) as new, " + " count(case operlogbiblio.action when 'change' then operlogbiblio.action end) as change, " + " count(case operlogbiblio.action when 'delete' then operlogbiblio.action when 'onlydeletebiblio' then 'delete' when 'onlydeletesubrecord' then 'delete' end) as del, " + " count(case operlogbiblio.action when 'copy' then operlogbiblio.action when 'onlycopybiblio' then 'copy' end) as copy, " + " count(case operlogbiblio.action when 'move' then operlogbiblio.action when 'onlymovebiblio' then 'move' end) as move, " + " count(*) as total " + " FROM operlogbiblio " + " left outer JOIN user ON operlogbiblio.operator <> '' AND operlogbiblio.operator = user.id " + " WHERE " + " operlogbiblio.date >= '" + strStartDate + "' AND operlogbiblio.date <= '" + strEndDate + "' " + " AND user.librarycodelist like '%," + strLibraryCode + ",%' " + " GROUP BY operlogbiblio.operator ORDER BY operlogbiblio.operator ;"; ; } else if (nNumber == 431) { // 431 表,册登记流水 string strTableName = "operlogitem"; strCommand = "select '', " + strTableName + ".action, " + strTableName + ".bibliorecpath, biblio.summary, item.itembarcode, " + strTableName + ".itemrecpath, " + strTableName + ".opertime, " + strTableName + ".operator " // + " FROM " + strTableName + " " + " left outer JOIN item ON " + strTableName + ".itemrecpath <> '' AND " + strTableName + ".itemrecpath = item.itemrecpath " + " left outer JOIN biblio ON " + strTableName + ".bibliorecpath <> '' AND " + strTableName + ".bibliorecpath = biblio.bibliorecpath " + " left outer JOIN user ON " + strTableName + ".operator <> '' AND " + strTableName + ".operator = user.id " + " WHERE " + " " + strTableName + ".date >= '" + strStartDate + "' AND " + strTableName + ".date <= '" + strEndDate + "' " + " AND user.librarycodelist like '%," + strLibraryCode + ",%' " + " ORDER BY " + strTableName + ".opertime ;"; } else if (nNumber == 411 // || nNumber == 431 || nNumber == 451) { // 411 表,订购流水 // 431 表,册登记流水 // 451 表,期登记流水 string strTableName = ""; if (nNumber == 411) strTableName = "operlogorder"; //else if (nNumber == 431) // strTableName = "operlogitem"; else if (nNumber == 451) strTableName = "operlogissue"; strCommand = "select '', " + strTableName + ".action, " + strTableName + ".bibliorecpath, biblio.summary, " + strTableName + ".itemrecpath, " + strTableName + ".opertime, " + strTableName + ".operator " // + " FROM " + strTableName + " " + " left outer JOIN biblio ON " + strTableName + ".bibliorecpath <> '' AND " + strTableName + ".bibliorecpath = biblio.bibliorecpath " + " left outer JOIN user ON " + strTableName + ".operator <> '' AND " + strTableName + ".operator = user.id " + " WHERE " + " " + strTableName + ".date >= '" + strStartDate + "' AND " + strTableName + ".date <= '" + strEndDate + "' " + " AND user.librarycodelist like '%," + strLibraryCode + ",%' " + " ORDER BY " + strTableName + ".opertime ;"; } else if (nNumber == 412 || nNumber == 432 || nNumber == 452) { // 412 表,每个工作人员订购各类工作量 // 432 表,每个工作人员册登记各类工作量 // 452 表,每个工作人员期登记各类工作量 string strTableName = ""; if (nNumber == 412) strTableName = "operlogorder"; else if (nNumber == 432) strTableName = "operlogitem"; else if (nNumber == 452) strTableName = "operlogissue"; strCommand = "select " + strTableName + ".operator, " // + " count(case " + strTableName + ".action when 'new' then " + strTableName + ".action end) as new, " + " count(case " + strTableName + ".action when 'change' then " + strTableName + ".action end) as change, " + " count(case " + strTableName + ".action when 'delete' then " + strTableName + ".action end) as del, " + " count(case " + strTableName + ".action when 'copy' then " + strTableName + ".action end) as copy, " + " count(case " + strTableName + ".action when 'move' then " + strTableName + ".action end) as move, " + " count(*) as total " + " FROM " + strTableName + " " + " left outer JOIN user ON " + strTableName + ".operator <> '' AND " + strTableName + ".operator = user.id " + " WHERE " + " " + strTableName + ".date >= '" + strStartDate + "' AND " + strTableName + ".date <= '" + strEndDate + "' " + " AND user.librarycodelist like '%," + strLibraryCode + ",%' " + " GROUP BY " + strTableName + ".operator " + " ORDER BY " + strTableName + ".operator ;"; } else if (nNumber == 441) { // 441 表,出纳流水 strCommand = "select '', operlogcircu.readerbarcode, reader.name, operlogcircu.action, operlogcircu.itembarcode, biblio.summary, operlogcircu.opertime , operlogcircu.operator " // + " FROM operlogcircu left outer JOIN item ON operlogcircu.itembarcode <> '' AND operlogcircu.itembarcode = item.itembarcode " + " left outer JOIN biblio ON item.bibliorecpath <> '' AND item.bibliorecpath = biblio.bibliorecpath " + " left outer JOIN reader ON operlogcircu.readerbarcode <> '' AND operlogcircu.readerbarcode = reader.readerbarcode " + " WHERE " + " operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND reader.librarycode = '" + strLibraryCode + "' " + " ORDER BY operlogcircu.opertime ;"; } else if (nNumber == 442) { // 442 表,每个工作人员各类工作量 strCommand = "select operlogcircu.operator, " // + " count(case operlogcircu.action when 'borrow' then operlogcircu.action end) as borrow, " + " count(case operlogcircu.action when 'renew' then operlogcircu.action end) as renew, " + " count(case operlogcircu.action when 'return' then operlogcircu.action end) as return, " + " count(case operlogcircu.action when 'lost' then operlogcircu.action end) as lost, " + " count(case operlogcircu.action when 'read' then operlogcircu.action end) as read, " + " count(*) as total " + " FROM operlogcircu " + " left outer JOIN reader ON operlogcircu.readerbarcode <> '' AND operlogcircu.readerbarcode = reader.readerbarcode " + " WHERE " + " operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND reader.librarycode = '" + strLibraryCode + "' " + " GROUP BY operlogcircu.operator " + " ORDER BY operlogcircu.operator ;"; } else if (nNumber == 443) { // 443 表,每个馆藏地点各类工作量 strCommand = "select item.location, " // + " count(case operlogcircu.action when 'borrow' then operlogcircu.action end) as borrow, " + " count(case operlogcircu.action when 'renew' then operlogcircu.action end) as renew, " + " count(case operlogcircu.action when 'return' then operlogcircu.action end) as return, " + " count(case operlogcircu.action when 'lost' then operlogcircu.action end) as lost, " + " count(case operlogcircu.action when 'read' then operlogcircu.action end) as read, " + " count(*) as total " + " FROM operlogcircu " + " left outer JOIN reader ON operlogcircu.readerbarcode <> '' AND operlogcircu.readerbarcode = reader.readerbarcode " + " left outer JOIN item ON operlogcircu.itembarcode <> '' AND operlogcircu.itembarcode = item.itembarcode " + " WHERE " + " operlogcircu.date >= '" + strStartDate + "' AND operlogcircu.date <= '" + strEndDate + "' " + " AND reader.librarycode = '" + strLibraryCode + "' " + " GROUP BY item.location ORDER BY item.location ;"; } else if (nNumber == 471) { #if NO // 471 表,违约金流水 strCommand = "select '', operlogamerce.action, operlogamerce.price, operlogamerce.unit, operlogamerce.amercerecpath, operlogamerce.reason, operlogamerce.itembarcode,biblio.summary, operlogamerce.readerbarcode, reader.name, operlogamerce.opertime, operlogamerce.operator " // + " FROM operlogamerce " + " left outer JOIN item ON operlogamerce.itembarcode <> '' AND operlogamerce.itembarcode <> '' AND operlogamerce.itembarcode = item.itembarcode " + " left outer JOIN biblio ON item.bibliorecpath <> '' AND item.bibliorecpath = biblio.bibliorecpath " + " left outer JOIN reader ON operlogamerce.readerbarcode <> '' AND operlogamerce.readerbarcode = reader.readerbarcode " // + " left outer JOIN user ON operlogamerce.operator = user.id " + " WHERE " + " operlogamerce.date >= '" + strStartDate + "' AND operlogamerce.date <= '" + strEndDate + "' " + " AND reader.librarycode = '" + strLibraryCode + "' " + " ORDER BY operlogamerce.opertime ;"; #endif // 471 表,违约金流水 strCommand = "select '', operlogamerce.action, operlogamerce.price, operlogamerce.unit, operlogamerce.amercerecpath, operlogamerce.reason, operlogamerce.itembarcode,biblio.summary, operlogamerce.readerbarcode, reader.name, operlogamerce.opertime, operlogamerce.operator " // + " FROM operlogamerce " + " left outer JOIN item ON operlogamerce.itembarcode <> '' AND operlogamerce.itembarcode <> '' AND operlogamerce.itembarcode = item.itembarcode " + " left outer JOIN biblio ON item.bibliorecpath <> '' AND item.bibliorecpath = biblio.bibliorecpath " + " left outer JOIN reader ON operlogamerce.readerbarcode <> '' AND operlogamerce.readerbarcode = reader.readerbarcode " + " WHERE " + " operlogamerce.date >= '" + strStartDate + "' AND operlogamerce.date <= '" + strEndDate + "' " + " AND operlogamerce.librarycode like '%," + strLibraryCode + ",%' " + " ORDER BY operlogamerce.opertime ;"; } else if (nNumber == 472) { /* select operlogamerce.operator, operlogamerce.unit, count(case operlogamerce.action when 'amerce' then operlogamerce.action end) as amerce, sum(case operlogamerce.action when 'amerce' then operlogamerce.price end) / 100.0 as amerce_money, count(case operlogamerce.action when 'undo' then operlogamerce.action end) as undo, sum(case operlogamerce.action when 'undo' then operlogamerce.price end) / 100.0 as undo_money, count(case operlogamerce.action when 'expire' then operlogamerce.action end) as expire, count(*) as total from operlogamerce left outer JOIN reader ON operlogamerce.readerbarcode = reader.readerbarcode WHERE reader.librarycode = '合肥望湖小学' GROUP BY operlogamerce.operator, operlogamerce.unit; * * */ #if NO // 472 表,每个工作人员违约金工作量 strCommand = "select operlogamerce.operator, " // + " operlogamerce.unit, " + " count(case operlogamerce.action when 'amerce' then operlogamerce.action end) as amerce_count," + " sum(case operlogamerce.action when 'amerce' then operlogamerce.price end) / 100.0 as amerce_money," + " count(case operlogamerce.action when 'modifyprice' then operlogamerce.action end) as modify_count," + " sum(case operlogamerce.action when 'modifyprice' then operlogamerce.price end) / 100.0 as modify_money," + " count(case operlogamerce.action when 'undo' then operlogamerce.action end) as undo_count, " + " sum(case operlogamerce.action when 'undo' then operlogamerce.price end) / 100.0 as undo_money, " + " count(case operlogamerce.action when 'expire' then operlogamerce.action end) as expire_count, " + " count(*) as total_count " + " FROM operlogamerce " + " left outer JOIN reader ON operlogamerce.readerbarcode <> '' AND operlogamerce.readerbarcode = reader.readerbarcode " + " WHERE " + " operlogamerce.date >= '" + strStartDate + "' AND operlogamerce.date <= '" + strEndDate + "' " + " AND reader.librarycode = '" + strLibraryCode + "' " + " GROUP BY operlogamerce.operator, operlogamerce.unit " + " ORDER BY operlogamerce.operator ;"; #endif // 472 表,每个工作人员违约金工作量 strCommand = "select operlogamerce.operator, " // + " operlogamerce.unit, " + " count(case operlogamerce.action when 'amerce' then operlogamerce.action end) as amerce_count," + " sum(case operlogamerce.action when 'amerce' then operlogamerce.price end) / 100.0 as amerce_money," + " count(case operlogamerce.action when 'modifyprice' then operlogamerce.action end) as modify_count," + " sum(case operlogamerce.action when 'modifyprice' then operlogamerce.price end) / 100.0 as modify_money," + " count(case operlogamerce.action when 'undo' then operlogamerce.action end) as undo_count, " + " sum(case operlogamerce.action when 'undo' then operlogamerce.price end) / 100.0 as undo_money, " + " count(case operlogamerce.action when 'expire' then operlogamerce.action end) as expire_count, " + " count(*) as total_count " + " FROM operlogamerce " + " WHERE " + " operlogamerce.date >= '" + strStartDate + "' AND operlogamerce.date <= '" + strEndDate + "' " + " AND operlogamerce.librarycode like '%," + strLibraryCode + ",%' " + " GROUP BY operlogamerce.operator, operlogamerce.unit " + " ORDER BY operlogamerce.operator ;"; } else if (nNumber == 481) { // 481 表,入馆登记流水 strCommand = "select '', operlogpassgate.action, operlogpassgate.gatename, operlogpassgate.readerbarcode, reader.name, operlogpassgate.opertime, operlogpassgate.operator " // + " FROM operlogpassgate " + " left outer JOIN reader ON operlogpassgate.readerbarcode <> '' AND operlogpassgate.readerbarcode = reader.readerbarcode " // + " left outer JOIN user ON operlogamerce.operator = user.id " + " WHERE " + " operlogpassgate.date >= '" + strStartDate + "' AND operlogpassgate.date <= '" + strEndDate + "' " + " AND reader.librarycode = '" + strLibraryCode + "' " + " ORDER BY operlogpassgate.opertime ;"; } else if (nNumber == 482) { // 482 表,每个门名称的入馆登记数量 strCommand = "select operlogpassgate.gatename, " // + " count(*) as pass_count, " + " count(*) as total_count " + " FROM operlogpassgate " + " left outer JOIN reader ON operlogpassgate.readerbarcode <> '' AND operlogpassgate.readerbarcode = reader.readerbarcode " + " WHERE " + " operlogpassgate.date >= '" + strStartDate + "' AND operlogpassgate.date <= '" + strEndDate + "' " + " AND reader.librarycode = '" + strLibraryCode + "' " + " GROUP BY operlogpassgate.gatename " + " ORDER BY operlogpassgate.gatename ;"; } else if (nNumber == 491) { // 491 表,获取对象流水 // TODO: 可以加上读者姓名和单位列 strCommand = "select '', operloggetres.action, operloggetres.xmlrecpath, biblio.summary, operloggetres.objectid, operloggetres.size, operloggetres.opertime, operloggetres.operator " // + " FROM operloggetres " + " left outer JOIN biblio ON operloggetres.xmlrecpath <> '' AND operloggetres.xmlrecpath = biblio.bibliorecpath " + " left outer JOIN reader ON operloggetres.operator <> '' AND operloggetres.operator = reader.readerbarcode " + " left outer JOIN user ON operloggetres.operator = user.id " + " WHERE " + " operloggetres.date >= '" + strStartDate + "' AND operloggetres.date <= '" + strEndDate + "' " + " AND ( reader.librarycode = '" + strLibraryCode + "' OR user.librarycodelist like '%," + strLibraryCode + ",%') " + " ORDER BY operloggetres.opertime ;"; } else if (nNumber == 492) { // 492 表,每个操作者获取对象的量 strCommand = "select operloggetres.operator, reader.name, reader.department, " // // + " operloggetres.unit, " + " count(case operloggetres.action when '' then operloggetres.action end) as get_count," + " sum(case operloggetres.action when '' then operloggetres.size end) as get_size," + " count(*) as total_count " + " FROM operloggetres " + " left outer JOIN reader ON operloggetres.operator <> '' AND operloggetres.operator = reader.readerbarcode " + " left outer JOIN user ON operloggetres.operator = user.id " + " WHERE " + " operloggetres.date >= '" + strStartDate + "' AND operloggetres.date <= '" + strEndDate + "' " + " AND ( reader.librarycode = '" + strLibraryCode + "' OR user.librarycodelist like '%," + strLibraryCode + ",%') " + " GROUP BY operloggetres.operator " + " ORDER BY operloggetres.operator ;"; } else { strError = "CreateWorkerReport() 中 strStyle=" + strStyle + " 没有分支处理"; return -1; } return 0; } // 创建分类报表,关于获取对象 // 1) 493 按照分类的获取对象数字 int CreateClassReportCommand( // string strLocation, // "名称/" string strLibraryCode, string strDateRange, string strStyle, string strClassType, List<string> filters, out string strCommand, out string strError) { strError = ""; strCommand = ""; string strStartDate = ""; string strEndDate = ""; try { // 将日期字符串解析为起止范围日期 // throw: // Exception DateTimeUtil.ParseDateRange(strDateRange, out strStartDate, out strEndDate); if (string.IsNullOrEmpty(strEndDate) == true) strEndDate = strStartDate; } catch (Exception) { strError = "日期范围字符串 '" + strDateRange + "' 格式不正确"; return -1; } if (StringUtil.IsInList("493", strStyle) == true) { /* select substr(class_clc.class,1,1) as class1, count(operloggetres.action) as get_count, sum(operloggetres.size) as get_size FROM operloggetres left outer JOIN reader ON operloggetres.operator <> '' AND operloggetres.operator = reader.readerbarcode left outer JOIN user ON operloggetres.operator = user.id JOIN class_clc ON class_clc.bibliorecpath = operloggetres.xmlrecpath where ... GROUP BY class1 ORDER BY class1 * * */ string strClassTableName = "class_" + strClassType; int nRet = PrepareDistinctClassTable( strClassTableName, out strError); if (nRet == -1) return -1; string strDistinctClassTableName = "class_" + strClassType + "_d"; string strClassColumn = BuildClassColumnFragment(strDistinctClassTableName, filters, "other"); #if NO strStartDate = strStartDate.Insert(6, "-").Insert(4, "-"); strEndDate = strEndDate.Insert(6, "-").Insert(4, "-"); #endif // 493 表 按照图书 *分类* 的获取对象数字 strCommand = "select " + strClassColumn + " as classhead, " + " count(operloggetres.action) as get_count, " + " sum(operloggetres.size) as get_size " + " FROM operloggetres " + " left outer JOIN reader ON operloggetres.operator <> '' AND operloggetres.operator = reader.readerbarcode " + " left outer JOIN user ON operloggetres.operator = user.id " + " LEFT OUTER JOIN " + strDistinctClassTableName + " ON operloggetres.xmlrecpath <> '' AND " + strDistinctClassTableName + ".bibliorecpath = operloggetres.xmlrecpath " + " WHERE " + " operloggetres.date >= '" + strStartDate + "' AND operloggetres.date <= '" + strEndDate + "' " + " AND ( reader.librarycode = '" + strLibraryCode + "' OR user.librarycodelist like '%," + strLibraryCode + ",%') " + " GROUP BY classhead ORDER BY classhead ;"; // left outer join 是包含了左边找不到右边的那些行, 然后 class 列为 NULL } else if (StringUtil.IsInList("???", strStyle) == true) { } else { strError = "不支持的 strStyle '" + strStyle + "'"; return -1; } return 0; } // 即将废弃 private void toolStripButton_printHtml_Click(object sender, EventArgs e) { HtmlPrintForm printform = new HtmlPrintForm(); printform.Text = "打印统计结果"; // printform.MainForm = Program.MainForm; Debug.Assert(this.OutputFileNames != null, ""); printform.Filenames = this.OutputFileNames; Program.MainForm.AppInfo.LinkFormState(printform, "printform_state"); printform.ShowDialog(this); Program.MainForm.AppInfo.UnlinkFormState(printform); } #region 统计结果 HTML 文件管理 /// <summary> /// 输出的 HTML 统计结果文件名集合 /// </summary> public List<string> OutputFileNames = new List<string>(); // 存放输出的html文件 int m_nFileNameSeed = 1; /// <summary> /// 获得一个新的输出文件名 /// </summary> /// <returns>输出文件名</returns> public string NewOutputFileName() { string strFileNamePrefix = Program.MainForm.DataDir + "\\~report_"; // string strFileNamePrefix = GetOutputFileNamePrefix(); string strFileName = strFileNamePrefix + "_" + this.m_nFileNameSeed.ToString() + ".html"; this.m_nFileNameSeed++; this.OutputFileNames.Add(strFileName); return strFileName; } /// <summary> /// 将字符串内容写入指定的文本文件。如果文件中已经存在内容,则被本次写入的覆盖 /// </summary> /// <param name="strFileName">文本文件名</param> /// <param name="strText">要写入文件的字符串</param> /// <param name="encoding">编码方式</param> public void WriteToOutputFile(string strFileName, string strText, Encoding encoding) { using (StreamWriter sw = new StreamWriter(strFileName, false, // append encoding)) { sw.Write(strText); } } /// <summary> /// 从磁盘上删除一个输出文件,并从 OutputFileNames 集合中移走其文件名 /// </summary> /// <param name="strFileName">文件名</param> public void DeleteOutputFile(string strFileName) { int nIndex = this.OutputFileNames.IndexOf(strFileName); if (nIndex != -1) this.OutputFileNames.RemoveAt(nIndex); try { File.Delete(strFileName); } catch { } } #endregion private void listView_libraryConfig_MouseUp(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Right) return; ContextMenu contextMenu = new ContextMenu(); MenuItem menuItem = null; menuItem = new MenuItem("修改分馆配置 (&M)"); menuItem.Click += new System.EventHandler(this.menu_modifyConfig_Click); if (this.listView_libraryConfig.SelectedItems.Count == 0) menuItem.Enabled = false; contextMenu.MenuItems.Add(menuItem); menuItem = new MenuItem("创建分馆配置(&C)"); menuItem.Click += new System.EventHandler(this.menu_newConfig_Click); contextMenu.MenuItems.Add(menuItem); // --- menuItem = new MenuItem("-"); contextMenu.MenuItems.Add(menuItem); menuItem = new MenuItem("自动创建全部分馆配置 (&A)"); menuItem.Click += new System.EventHandler(this.menu_autoConfig_Click); if (this.listView_libraryConfig.Items.Count != 0) menuItem.Enabled = false; contextMenu.MenuItems.Add(menuItem); menuItem = new MenuItem("增全分馆配置 [" + this.listView_libraryConfig.SelectedItems.Count.ToString() + "] (&A)"); menuItem.Click += new System.EventHandler(this.menu_autoAppendConfig_Click); if (this.listView_libraryConfig.Items.Count == 0) menuItem.Enabled = false; contextMenu.MenuItems.Add(menuItem); // --- menuItem = new MenuItem("-"); contextMenu.MenuItems.Add(menuItem); menuItem = new MenuItem("删除 [" + this.listView_libraryConfig.SelectedItems.Count.ToString() + "] (&S)"); menuItem.Click += new System.EventHandler(this.menu_deleteConfig_Click); if (this.listView_libraryConfig.SelectedItems.Count == 0) menuItem.Enabled = false; contextMenu.MenuItems.Add(menuItem); // --- menuItem = new MenuItem("-"); contextMenu.MenuItems.Add(menuItem); #if NO string strLibraryCode = ""; if (this.listView_libraryConfig.SelectedItems.Count == 1) strLibraryCode = ListViewUtil.GetItemText(this.listView_libraryConfig.SelectedItems[0], 0); #endif menuItem = new MenuItem("创建选定分馆的最新报表 [" + this.listView_libraryConfig.SelectedItems.Count.ToString() + "] (&S)"); menuItem.Click += new System.EventHandler(this.menu_createSelectedLibraryReport_Click); if (this.listView_libraryConfig.SelectedItems.Count == 0) menuItem.Enabled = false; contextMenu.MenuItems.Add(menuItem); #if NO // 创建报表 { menuItem = new MenuItem("创建报表(&R)"); contextMenu.MenuItems.Add(menuItem); MenuItem subMenuItem = new MenuItem("借阅清单 (&B)..."); subMenuItem.Click += new System.EventHandler(this.menu_createBorrowListReport_Click); if (this.listView_libraryConfig.SelectedItems.Count == 0) subMenuItem.Enabled = false; menuItem.MenuItems.Add(subMenuItem); // --- subMenuItem = new MenuItem("-"); menuItem.MenuItems.Add(subMenuItem); } #endif contextMenu.Show(this.listView_libraryConfig, new Point(e.X, e.Y)); } // 根据配置文件类型,找到配置文件名 static int FindCfgFileByType(XmlNode nodeLibrary, string strTypeParam, out string strCfgFile, out string strError) { strError = ""; XmlNodeList nodes = nodeLibrary.SelectNodes("reports/report"); foreach (XmlNode node in nodes) { string strName = DomUtil.GetAttr(node, "name"); string strType = DomUtil.GetAttr(node, "type"); if (strType == strTypeParam) { strCfgFile = DomUtil.GetAttr(node, "cfgFile"); return 1; } } strCfgFile = ""; return 0; } // 增全分馆配置 void menu_autoAppendConfig_Click(object sender, EventArgs e) { string strError = ""; int nRet = 0; bool bChanged = false; foreach (ListViewItem item in this.listView_libraryConfig.SelectedItems) { string strLibraryCode = ListViewUtil.GetItemText(item, 0); strLibraryCode = GetOriginLibraryCode(strLibraryCode); XmlNode nodeLibrary = this._cfg.GetLibraryNode(strLibraryCode); if (nodeLibrary == null) { strError = "在配置文件中没有找到馆代码为 '" + strLibraryCode + "' 的 <library> 元素"; goto ERROR1; } LibraryReportConfigForm dlg = new LibraryReportConfigForm(); // dlg.MainForm = Program.MainForm; dlg.ReportForm = this; dlg.LoadData(nodeLibrary); dlg.ModifyMode = true; // 自动增全报表配置 // return: // -1 出错 // >=0 新增的报表类型个数 nRet = dlg.AutoAppend(out strError); if (nRet == -1) goto ERROR1; if (nRet > 0) { bChanged = true; dlg.SetData(nodeLibrary); } } if (bChanged == true) this._cfg.Save(); return; ERROR1: this.Invoke((Action)(() => { MessageBox.Show(this, strError); })); } // 首次自动创建全部分馆的配置 void menu_autoConfig_Click(object sender, EventArgs e) { string strError = ""; int nRet = 0; LibraryReportConfigForm dlg = new LibraryReportConfigForm(); MainForm.SetControlFont(dlg, this.Font, false); // dlg.MainForm = Program.MainForm; dlg.ReportForm = this; List<string> librarycodes = Program.MainForm.GetAllLibraryCode(); foreach (string code in librarycodes) { nRet = dlg.AutoCreate(code, out strError); if (nRet == -1) goto ERROR1; XmlNode nodeLibrary = null; // 创建一个新的 <library> 元素。要对 code 属性进行查重 // parameters: // -1 出错 // 0 成功 // 1 已经有这个 code 属性的元素了 nRet = this._cfg.CreateNewLibraryNode(dlg.LibraryCode, out nodeLibrary, out strError); if (nRet == -1) goto ERROR1; if (nRet == 1) continue; dlg.SetData(nodeLibrary); ListViewItem item = new ListViewItem(); ListViewUtil.ChangeItemText(item, 0, GetDisplayLibraryCode(dlg.LibraryCode)); this.listView_libraryConfig.Items.Add(item); ListViewUtil.SelectLine(item, true); } this._cfg.Save(); return; ERROR1: this.Invoke((Action)(() => { MessageBox.Show(this, strError); })); } // 修改一个分馆配置 void menu_modifyConfig_Click(object sender, EventArgs e) { string strError = ""; //int nRet = 0; if (this.listView_libraryConfig.SelectedItems.Count == 0) { strError = "尚未选定要修改的事项"; goto ERROR1; } ListViewItem item = this.listView_libraryConfig.SelectedItems[0]; string strLibraryCode = ListViewUtil.GetItemText(item, 0); strLibraryCode = GetOriginLibraryCode(strLibraryCode); XmlNode nodeLibrary = this._cfg.GetLibraryNode(strLibraryCode); if (nodeLibrary == null) { strError = "在配置文件中没有找到馆代码为 '" + strLibraryCode + "' 的 <library> 元素"; goto ERROR1; } LibraryReportConfigForm dlg = new LibraryReportConfigForm(); MainForm.SetControlFont(dlg, this.Font, false); // dlg.MainForm = Program.MainForm; dlg.ReportForm = this; dlg.LoadData(nodeLibrary); dlg.ModifyMode = true; Program.MainForm.AppInfo.LinkFormState(dlg, "LibraryReportConfigForm_state"); dlg.UiState = Program.MainForm.AppInfo.GetString(GetReportSection(), "LibraryReportConfigForm_ui_state", ""); dlg.ShowDialog(this); Program.MainForm.AppInfo.SetString(GetReportSection(), "LibraryReportConfigForm_ui_state", dlg.UiState); Program.MainForm.AppInfo.UnlinkFormState(dlg); if (dlg.DialogResult == System.Windows.Forms.DialogResult.Cancel) return; dlg.SetData(nodeLibrary); #if NO ListViewUtil.ChangeItemText(item, 0, dlg.LibraryCode); #endif this._cfg.Save(); return; ERROR1: this.Invoke((Action)(() => { MessageBox.Show(this, strError); })); } // 创建一个新的分馆配置 void menu_newConfig_Click(object sender, EventArgs e) { string strError = ""; int nRet = 0; LibraryReportConfigForm dlg = new LibraryReportConfigForm(); MainForm.SetControlFont(dlg, this.Font, false); // dlg.MainForm = Program.MainForm; dlg.ReportForm = this; nRet = dlg.AutoCreate("", out strError); if (nRet == -1) goto ERROR1; REDO: Program.MainForm.AppInfo.LinkFormState(dlg, "LibraryReportConfigForm_state"); dlg.UiState = Program.MainForm.AppInfo.GetString(GetReportSection(), "LibraryReportConfigForm_ui_state", ""); dlg.ShowDialog(this); Program.MainForm.AppInfo.SetString(GetReportSection(), "LibraryReportConfigForm_ui_state", dlg.UiState); Program.MainForm.AppInfo.UnlinkFormState(dlg); if (dlg.DialogResult == System.Windows.Forms.DialogResult.Cancel) return; XmlNode nodeLibrary = null; // 创建一个新的 <library> 元素。要对 code 属性进行查重 // parameters: // -1 出错 // 0 成功 // 1 已经有这个 code 属性的元素了 nRet = this._cfg.CreateNewLibraryNode(dlg.LibraryCode, out nodeLibrary, out strError); if (nRet == -1) goto ERROR1; if (nRet == 1) { this.Invoke((Action)(() => { MessageBox.Show(this, strError + "\r\n\r\n请修改馆代码"); })); goto REDO; } dlg.SetData(nodeLibrary); ListViewItem item = new ListViewItem(); ListViewUtil.ChangeItemText(item, 0, GetDisplayLibraryCode(dlg.LibraryCode)); this.listView_libraryConfig.Items.Add(item); ListViewUtil.SelectLine(item, true); this._cfg.Save(); return; ERROR1: this.Invoke((Action)(() => { MessageBox.Show(this, strError); })); } // 删除选定的分馆配置 void menu_deleteConfig_Click(object sender, EventArgs e) { string strError = ""; if (this.listView_libraryConfig.SelectedItems.Count == 0) { strError = "尚未选定要删除的事项"; goto ERROR1; } DialogResult result = MessageBox.Show(this, "确实要删除选定的 " + this.listView_libraryConfig.SelectedItems.Count.ToString() + " 个事项?", "ReportForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result != DialogResult.Yes) return; foreach (ListViewItem item in this.listView_libraryConfig.SelectedItems) { string strLibraryCode = ListViewUtil.GetItemText(item, 0); strLibraryCode = GetOriginLibraryCode(strLibraryCode); XmlNode nodeLibrary = this._cfg.GetLibraryNode(strLibraryCode); if (nodeLibrary == null) { strError = "在配置文件中没有找到馆代码为 '" + strLibraryCode + "' 的 <library> 元素"; // goto ERROR1; continue; } nodeLibrary.ParentNode.RemoveChild(nodeLibrary); } ListViewUtil.DeleteSelectedItems(this.listView_libraryConfig); if (this._cfg != null) this._cfg.Save(); return; ERROR1: this.Invoke((Action)(() => { MessageBox.Show(this, strError); })); } // 保存分馆参数配置 private void toolStripButton_libraryConfig_save_Click(object sender, EventArgs e) { if (this._cfg != null) this._cfg.Save(); } private void listView_libraryConfig_DoubleClick(object sender, EventArgs e) { menu_modifyConfig_Click(sender, e); } // 获得本窗口选用了的馆代码 // parameters: // bAll 是否返回全部分馆的关代码? true 返回全部;false 只返回选定了的 public List<string> GetLibraryCodes(bool bAll = true) { List<string> results = new List<string>(); foreach (ListViewItem item in this.listView_libraryConfig.Items) { if (bAll == false && item.Selected == false) continue; string strLibraryCode = ListViewUtil.GetItemText(item, 0); strLibraryCode = GetOriginLibraryCode(strLibraryCode); results.Add(strLibraryCode); } return results; } // 本地库的版本号 // 0.01 (2014/4/30) 第一个版本 // 0.02 (2014/5/6) item 表 增加了两个 index: item_itemrecpath_index 和 item_biliorecpath_index // 0.03 (2014/5/29) item 表增加了 borrower borrowtime borrowperiod returningtime 等字段 // 0.04 (2014/6/2) breakpoint 文件根元素下增加了 classStyles 元素 // 0.05 (2014/6/12) item 表增加了 price unit 列; operlogamerce 表的 price 列分开为 price 和 unit 列 // 0.06 (2014/6/16) operlogxxx 表中增加了 subno 字段 // 0.07 (2014/6/19) operlogitem 表增加了 itembarcode 字段 // 0.08 (2014/11/6) reader 表增加了 state 字段 // 0.09 (2015/7/14) 增加了 operlogpassgate 和 operloggetres 表 // 0.10 (2016/5/5) 给每个 operlogxxx 表增加了 librarycode 字段 // 0.11 (2016/12/8) 以前版本 operlogamerce 中 action 为 undo 的行,price 字段内容都为空,会导致 472 报表中统计出来的实收金额偏大,这个版本修正了这个 bug static string _local_version = "0.11"; // TODO: 最好把第一次初始化本地 sql 表的动作也纳入 XML 文件中,这样做单项任务的时候,就不会毁掉其他的表 // 创建批处理计划 // 根元素的 state 属性, 值为 first 表示正在进行首次创建,尚未完成; daily 表示已经创建完,进入每日同步阶段 int BuildPlan(string strTypeList, out XmlDocument task_dom, out string strError) { strError = ""; long lRet = 0; int nRet = 0; EnableControls(false); this.ChannelDoEvents = !this.InvokeRequired; stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在计划任务 ..."); stop.BeginLoop(); try { task_dom = new XmlDocument(); task_dom.LoadXml("<root />"); // 开始处理时的日期 string strEndDate = DateTimeUtil.DateTimeToString8(DateTime.Now); DomUtil.SetAttr(task_dom.DocumentElement, "version", _local_version); DomUtil.SetAttr(task_dom.DocumentElement, "state", "first"); // 表示首次创建尚未完成 // 记载首次创建的结束时间点 DomUtil.SetAttr(task_dom.DocumentElement, "end_date", strEndDate); // DomUtil.SetAttr(task_dom.DocumentElement, "index", lCount.ToString()); // *** 创建用户表 if (strTypeList == "*" || StringUtil.IsInList("user", strTypeList) == true) { XmlNode node = task_dom.CreateElement("user"); task_dom.DocumentElement.AppendChild(node); } // *** 创建 item 表 if (strTypeList == "*" || StringUtil.IsInList("item", strTypeList) == true) { // 获得全部实体库名 List<string> item_dbnames = new List<string>(); if (Program.MainForm.BiblioDbProperties != null) { for (int i = 0; i < Program.MainForm.BiblioDbProperties.Count; i++) { BiblioDbProperty property = Program.MainForm.BiblioDbProperties[i]; if (String.IsNullOrEmpty(property.ItemDbName) == false) item_dbnames.Add(property.ItemDbName); } } // 获得每个实体库的尺寸 foreach (string strItemDbName in item_dbnames) { stop.SetMessage("正在计划任务 检索 " + strItemDbName + " ..."); // 此处检索仅获得命中数即可 lRet = this.Channel.SearchItem(stop, strItemDbName, "", // -1, "__id", "left", "zh", null, // strResultSetName "", // strSearchStyle "", //strOutputStyle, // (bOutputKeyCount == true ? "keycount" : ""), out strError); if (lRet == -1) return -1; XmlNode node = task_dom.CreateElement("database"); task_dom.DocumentElement.AppendChild(node); DomUtil.SetAttr(node, "name", strItemDbName); DomUtil.SetAttr(node, "type", "item"); DomUtil.SetAttr(node, "count", lRet.ToString()); } } // *** 创建 reader 表 if (strTypeList == "*" || StringUtil.IsInList("reader", strTypeList) == true) { // 获得全部读者库名 List<string> reader_dbnames = new List<string>(); if (Program.MainForm.ReaderDbNames != null) { foreach (string s in Program.MainForm.ReaderDbNames) { if (String.IsNullOrEmpty(s) == false) reader_dbnames.Add(s); } } // foreach (string strReaderDbName in reader_dbnames) { stop.SetMessage("正在计划任务 检索 " + strReaderDbName + " ..."); // 此处检索仅获得命中数即可 lRet = this.Channel.SearchReader(stop, strReaderDbName, "", // -1, "__id", "left", "zh", null, // strResultSetName "", //strOutputStyle, // (bOutputKeyCount == true ? "keycount" : ""), out strError); if (lRet == -1) return -1; XmlNode node = task_dom.CreateElement("database"); task_dom.DocumentElement.AppendChild(node); DomUtil.SetAttr(node, "name", strReaderDbName); DomUtil.SetAttr(node, "type", "reader"); DomUtil.SetAttr(node, "count", lRet.ToString()); } } // *** 创建 biblio 表 // *** 创建 class 表 if (strTypeList == "*" || StringUtil.IsInList("biblio", strTypeList) == true) { // 获得全部书目库名 List<string> biblio_dbnames = new List<string>(); if (Program.MainForm.BiblioDbProperties != null) { foreach (BiblioDbProperty prop in Program.MainForm.BiblioDbProperties) { if (String.IsNullOrEmpty(prop.DbName) == false) biblio_dbnames.Add(prop.DbName); } } #if NO // 获得所有分类号检索途径 style List<string> styles = new List<string>(); nRet = GetClassFromStyles(out styles, out strError); if (nRet == -1) return -1; #endif // 记忆书目库的分类号 style 列表 nRet = MemoryClassFromStyles(task_dom.DocumentElement, out strError); if (nRet == -1) return -1; if (nRet == 0) { DialogResult result = DialogResult.No; string strText = strError; this.Invoke((Action)(() => { result = MessageBox.Show(this, strText + "\r\n\r\n建议先中断处理,配置好书目库的分类号检索点再重新创建本地存储。如果此时继续处理,则会无法同步分类号信息,以后也无法创建和分类号有关的报表。\r\n\r\n是否继续处理?", "ReportForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); })); if (result == System.Windows.Forms.DialogResult.No) return -1; // } // 从计划文件中获得所有分类号检索途径 style List<string> styles = new List<string>(); nRet = GetClassFromStyles( task_dom.DocumentElement, out styles, out strError); if (nRet == -1) return -1; // foreach (string strBiblioDbName in biblio_dbnames) { stop.SetMessage("正在计划任务 检索 " + strBiblioDbName + " ..."); string strQueryXml = ""; // 此处检索仅获得命中数即可 lRet = this.Channel.SearchBiblio(stop, strBiblioDbName, "", // -1, "recid", // "__id", "left", "zh", null, // strResultSetName "", // strSearchStyle "", //strOutputStyle, // (bOutputKeyCount == true ? "keycount" : ""), "", out strQueryXml, out strError); if (lRet == -1) return -1; XmlNode node = task_dom.CreateElement("database"); task_dom.DocumentElement.AppendChild(node); DomUtil.SetAttr(node, "name", strBiblioDbName); DomUtil.SetAttr(node, "type", "biblio"); DomUtil.SetAttr(node, "count", lRet.ToString()); foreach (string strStyle in styles) { stop.SetMessage("正在计划任务 检索 " + strBiblioDbName + " " + strStyle + " ..."); // 此处检索仅获得命中数即可 lRet = this.Channel.SearchBiblio(stop, strBiblioDbName, "", // -1, strStyle, // "__id", "left", // this.textBox_queryWord.Text == "" ? "left" : "exact", // 原来为left 2007/10/18 changed "zh", null, // strResultSetName "", // strSearchStyle "keyid", //strOutputStyle, // (bOutputKeyCount == true ? "keycount" : ""), "", out strQueryXml, out strError); if (lRet == -1) { if (this.Channel.ErrorCode == ErrorCode.FromNotFound) continue; return -1; } string strClassTableName = "class_" + strStyle; XmlNode class_node = task_dom.CreateElement("class"); node.AppendChild(class_node); DomUtil.SetAttr(class_node, "from_style", strStyle); DomUtil.SetAttr(class_node, "class_table_name", strClassTableName); DomUtil.SetAttr(class_node, "count", lRet.ToString()); } } } // *** 创建日志表 if (strTypeList == "*" || StringUtil.IsInList("operlog", strTypeList) == true) { // return: // -1 出错 // 0 没有找到 // 1 找到 nRet = GetFirstOperLogDate( LogType.OperLog | LogType.AccessLog, out string strFirstDate, out strError); if (nRet == -1) { strError = "获得第一个操作日志文件日期时出错: " + strError; return -1; } // 获得日志文件中记录的总数 // parameters: // strDate 日志文件的日期,8 字符 // return: // -2 此类型的日志在 dp2library 端尚未启用 // -1 出错 // 0 日志文件不存在,或者记录数为 0 // >0 记录数 long lCount = OperLogLoader.GetOperLogCount( stop, this.Channel, strEndDate, LogType.OperLog, out strError); if (lCount < 0) return -1; DomUtil.SetAttr(task_dom.DocumentElement, "index", lCount.ToString()); if (nRet == 1) { // 记载第一个日志文件日期 DomUtil.SetAttr(task_dom.DocumentElement, "first_operlog_date", strFirstDate); Program.MainForm.AppInfo.SetString(GetReportSection(), "daily_report_end_date", strFirstDate); Program.MainForm.AppInfo.Save(); // 为防止程序中途崩溃丢失记忆,这里预先保存一下 XmlNode node = task_dom.CreateElement("operlog"); task_dom.DocumentElement.AppendChild(node); DomUtil.SetAttr(node, "start_date", strFirstDate); // "20060101" DomUtil.SetAttr(node, "end_date", strEndDate + ":0-" + (lCount - 1).ToString()); } } // *** 创建访问日志表 if (strTypeList == "*" || StringUtil.IsInList("accesslog", strTypeList) == true) { string strFirstDate = ""; // return: // -1 出错 // 0 没有找到 // 1 找到 nRet = GetFirstOperLogDate( LogType.AccessLog, out strFirstDate, out strError); if (nRet == -1) { strError = "获得第一个访问日志文件日期时出错: " + strError; return -1; } // 获得日志文件中记录的总数 // parameters: // strDate 日志文件的日期,8 字符 // return: // -2 此类型的日志在 dp2library 端尚未启用 // -1 出错 // 0 日志文件不存在,或者记录数为 0 // >0 记录数 long lCount = OperLogLoader.GetOperLogCount( stop, this.Channel, strEndDate, LogType.AccessLog, out strError); if (lCount == -1) return -1; if (nRet == 1 && lCount >= 0) { // 记载第一个访问日志文件日期 DomUtil.SetAttr(task_dom.DocumentElement, "first_accesslog_date", strFirstDate); XmlNode node = task_dom.CreateElement("accesslog"); task_dom.DocumentElement.AppendChild(node); DomUtil.SetAttr(node, "start_date", strFirstDate); // "20060101" DomUtil.SetAttr(node, "end_date", strEndDate + ":0-" + (lCount - 1).ToString()); } } return 0; } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); stop.HideProgress(); EnableControls(true); } } // 获得第一个(实有的)日志文件日期 // return: // -1 出错 // 0 没有找到 // 1 找到 int GetFirstOperLogDate( LogType logType, out string strFirstDate, out string strError) { strFirstDate = ""; strError = ""; DigitalPlatform.LibraryClient.localhost.OperLogInfo[] records = null; List<string> dates = new List<string>(); List<string> styles = new List<string>(); if ((logType & LogType.OperLog) != 0) styles.Add("getfilenames"); if ((logType & LogType.AccessLog) != 0) styles.Add("getfilenames,accessLog"); if (styles.Count == 0) { strError = "logStyle 参数值中至少要包含一种类型"; return -1; } foreach (string style in styles) { // 获得日志 // return: // -1 error // 0 file not found // 1 succeed // 2 超过范围,本次调用无效 long lRet = this.Channel.GetOperLogs( null, "", 0, -1, 1, style, // "getfilenames", "", // strFilter out records, out strError); if (lRet == -1) return -1; if (lRet == 0) continue; if (records == null || records.Length < 1) { strError = "records error"; return -1; } if (string.IsNullOrEmpty(records[0].Xml) == true || records[0].Xml.Length < 8) { strError = "records[0].Xml error"; return -1; } dates.Add(records[0].Xml.Substring(0, 8)); } if (dates.Count == 0) return 0; // 取较小的一个 if (dates.Count > 1) dates.Sort(); strFirstDate = dates[0]; return 1; } ProgressEstimate _estimate = new ProgressEstimate(); string GetProgressTimeString(long lProgressValue) { #if NO string strStage = ""; if (this._stage >= 0) strStage = "第 " + (this._stage + 1).ToString() + " 阶段"; #endif return "剩余时间 " + ProgressEstimate.Format(_estimate.Estimate(lProgressValue)) + " 已经过时间 " + ProgressEstimate.Format(_estimate.delta_passed); } // 初始化若干 operlog 表 int CreateOperLogTables(out string strError) { strError = ""; // string[] types = {"circu" }; foreach (string type in OperLogTable.DbTypes) { int nRet = OperLogTable.CreateOperLogTable( type, this._connectionString, out strError); if (nRet == -1) return -1; } return 0; } // 执行首次创建本地存储的计划 // parameters: // task_dom 存储了计划信息的 XMlDocument 对象。执行后,里面的信息会记载了断点信息等。如果完全完成,则保存前可以仅仅留下结束点信息 int DoPlan(ref XmlDocument task_dom, out string strError) { strError = ""; int nRet = 0; EnableControls(false); this.ChannelDoEvents = !this.InvokeRequired; stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在创建本地存储 ..."); stop.BeginLoop(); try { this._connectionString = GetOperlogConnectionString(); // SQLiteUtil.GetConnectionString(Program.MainForm.UserDir, "operlog.bin"); // 初始化各种表,除了 operlogXXX 表以外 string strInitilized = DomUtil.GetAttr(task_dom.DocumentElement, "initial_tables"); if (strInitilized != "finish") { stop.SetMessage("正在删除残余的数据库文件 ..."); // 删除以前遗留的数据库文件 string strDatabaseFile = Path.Combine(GetBaseDirectory(), "operlog.bin"); if (File.Exists(strDatabaseFile) == true) { File.Delete(strDatabaseFile); } stop.SetMessage("正在初始化本地数据库 ..."); nRet = ItemLine.CreateItemTable( this._connectionString, out strError); if (nRet == -1) return -1; nRet = ReaderLine.CreateReaderTable( this._connectionString, out strError); if (nRet == -1) return -1; nRet = BiblioLine.CreateBiblioTable( this._connectionString, out strError); if (nRet == -1) return -1; { List<string> styles = new List<string>(); // 获得所有分类号检索途径 style nRet = GetClassFromStyles( task_dom.DocumentElement, out styles, out strError); if (nRet == -1) return -1; foreach (string strStyle in styles) { nRet = ClassLine.CreateClassTable( this._connectionString, "class_" + strStyle, out strError); if (nRet == -1) return -1; } } DomUtil.SetAttr(task_dom.DocumentElement, "initial_tables", "finish"); } // 先累计总记录数,以便设置进度条 long lTotalCount = 0; XmlNodeList nodes = task_dom.DocumentElement.SelectNodes("database/class | database"); foreach (XmlNode node in nodes) { string strState = DomUtil.GetAttr(node, "state"); if (strState == "finish") continue; long lCount = 0; nRet = DomUtil.GetIntegerParam(node, "count", 0, out lCount, out strError); if (nRet == -1) return -1; lTotalCount += lCount; } stop.SetProgressRange(0, lTotalCount * 2); // 第一阶段,占据进度条一半 long lProgress = 0; _estimate.SetRange(0, lTotalCount * 2); _estimate.StartEstimate(); foreach (XmlNode node in task_dom.DocumentElement.ChildNodes) { if (node.NodeType != XmlNodeType.Element) continue; if (node.Name == "database") { string strDbName = DomUtil.GetAttr(node, "name"); string strType = DomUtil.GetAttr(node, "type"); string strState = DomUtil.GetAttr(node, "state"); long lIndex = 0; nRet = DomUtil.GetIntegerParam(node, "index", 0, out lIndex, out strError); if (nRet == -1) return -1; long lCurrentCount = 0; nRet = DomUtil.GetIntegerParam(node, "count", 0, out lCurrentCount, out strError); if (nRet == -1) return -1; if (strType == "item" && strState != "finish") { try { nRet = BuildItemRecords( strDbName, lCurrentCount, ref lProgress, ref lIndex, out strError); } catch { DomUtil.SetAttr(node, "index", lIndex.ToString()); throw; } if (nRet == -1) { DomUtil.SetAttr(node, "index", lIndex.ToString()); return -1; } DomUtil.SetAttr(node, "state", "finish"); } if (strType == "reader" && strState != "finish") { try { nRet = BuildReaderRecords( strDbName, lCurrentCount, ref lProgress, ref lIndex, out strError); } catch { DomUtil.SetAttr(node, "index", lIndex.ToString()); throw; } if (nRet == -1) { DomUtil.SetAttr(node, "index", lIndex.ToString()); return -1; } DomUtil.SetAttr(node, "state", "finish"); } if (strType == "biblio") { if (strState != "finish") { try { nRet = BuildBiblioRecords( strDbName, lCurrentCount, ref lProgress, ref lIndex, out strError); } catch { DomUtil.SetAttr(node, "index", lIndex.ToString()); throw; } if (nRet == -1) { DomUtil.SetAttr(node, "index", lIndex.ToString()); return -1; } DomUtil.SetAttr(node, "state", "finish"); } XmlNodeList class_nodes = node.SelectNodes("class"); foreach (XmlNode class_node in class_nodes) { string strFromStyle = DomUtil.GetAttr(class_node, "from_style"); string strClassTableName = DomUtil.GetAttr(class_node, "class_table_name"); strState = DomUtil.GetAttr(class_node, "state"); lIndex = 0; nRet = DomUtil.GetIntegerParam(class_node, "index", 0, out lIndex, out strError); if (nRet == -1) return -1; // nRet = DomUtil.GetIntegerParam(class_node, "count", 0, out lCurrentCount, out strError); if (nRet == -1) return -1; if (strState != "finish") { try { nRet = BuildClassRecords( strDbName, strFromStyle, strClassTableName, lCurrentCount, ref lProgress, ref lIndex, out strError); } catch { DomUtil.SetAttr(class_node, "index", lIndex.ToString()); throw; } if (nRet == -1) { DomUtil.SetAttr(class_node, "index", lIndex.ToString()); return -1; } DomUtil.SetAttr(class_node, "state", "finish"); } } } } if (node.Name == "user") { string strState = DomUtil.GetAttr(node, "state"); if (strState != "finish") { nRet = DoCreateUserTable( out strError); if (nRet == -1) { return -1; } DomUtil.SetAttr(node, "state", "finish"); } } if (node.Name == "operlog") { string strTableInitilized = DomUtil.GetAttr(node, "initial_tables"); string strStartDate = DomUtil.GetAttr(node, "start_date"); string strEndDate = DomUtil.GetAttr(node, "end_date"); string strState = DomUtil.GetAttr(node, "state"); if (string.IsNullOrEmpty(strStartDate) == true) { // strStartDate = "20060101"; strError = "start_date 属性值不应为空: " + node.OuterXml; return -1; } if (string.IsNullOrEmpty(strEndDate) == true) { // strEndDate = DateTimeUtil.DateTimeToString8(DateTime.Now); strError = "end_date 属性值不应为空: " + node.OuterXml; return -1; } if (strTableInitilized != "finish") { stop.SetMessage("正在初始化本地数据库的日志表 ..."); if (this.InvokeRequired == false) Application.DoEvents(); nRet = CreateOperLogTables(out strError); if (nRet == -1) return -1; DomUtil.SetAttr(node, "initial_tables", "finish"); } if (strState != "finish") { string strLastDate = ""; long lLastIndex = 0; // TODO: 中断时断点记载 // TODO: 进度条应该是重新设置的 nRet = DoCreateOperLogTable( -1, strStartDate, strEndDate, LogType.OperLog, out strLastDate, out lLastIndex, out strError); if (nRet == -1) { if (string.IsNullOrEmpty(strLastDate) == false) DomUtil.SetAttr(node, "start_date", strLastDate + ":" + lLastIndex.ToString() + "-"); return -1; } DomUtil.SetAttr(node, "state", "finish"); } } if (node.Name == "accesslog") { string strTableInitilized = DomUtil.GetAttr(node, "initial_tables"); string strStartDate = DomUtil.GetAttr(node, "start_date"); string strEndDate = DomUtil.GetAttr(node, "end_date"); string strState = DomUtil.GetAttr(node, "state"); if (string.IsNullOrEmpty(strStartDate) == true) { strError = "start_date 属性值不应为空: " + node.OuterXml; return -1; } if (string.IsNullOrEmpty(strEndDate) == true) { strError = "end_date 属性值不应为空: " + node.OuterXml; return -1; } if (strTableInitilized != "finish") { // 前面应该已经初始化过了 DomUtil.SetAttr(node, "initial_tables", "finish"); } if (strState != "finish") { string strLastDate = ""; long lLastIndex = 0; // TODO: 中断时断点记载 // TODO: 进度条应该是重新设置的 nRet = DoCreateOperLogTable( -1, strStartDate, strEndDate, LogType.AccessLog, out strLastDate, out lLastIndex, out strError); if (nRet == -1) { if (string.IsNullOrEmpty(strLastDate) == false) DomUtil.SetAttr(node, "start_date", strLastDate + ":" + lLastIndex.ToString() + "-"); return -1; } DomUtil.SetAttr(node, "state", "finish"); } } } // TODO: 全部完成后,需要在 task_dom 中清除不必要的信息 DomUtil.SetAttr(task_dom.DocumentElement, "state", "daily"); // 表示首次创建已经完成,进入每日同步阶段 return 0; } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); stop.HideProgress(); EnableControls(true); } } // 创建 user 表 int DoCreateUserTable(out string strError) { strError = ""; stop.SetMessage("正在初始化本地数据库的用户表 ..."); if (this.InvokeRequired == false) Application.DoEvents(); this._connectionString = GetOperlogConnectionString(); int nRet = UserLine.CreateUserTable( this._connectionString, out strError); if (nRet == -1) return -1; using (SQLiteConnection connection = new SQLiteConnection(this._connectionString)) { connection.Open(); int nStart = 0; for (; ; ) { UserInfo[] users = null; long lRet = Channel.GetUser( stop, "list", "", nStart, -1, out users, out strError); if (lRet == -1) return -1; if (lRet == 0) { strError = "不存在用户信息。"; return 0; // not found } Debug.Assert(users != null, ""); List<UserLine> lines = new List<UserLine>(); for (int i = 0; i < users.Length; i++) { UserInfo info = users[i]; UserLine line = new UserLine(); line.ID = info.UserName; line.Rights = info.Rights; line.LibraryCodeList = "," + info.LibraryCode + ","; lines.Add(line); } // 插入一批用户记录 nRet = UserLine.AppendUserLines( connection, lines, out strError); if (nRet == -1) return -1; nStart += users.Length; if (nStart >= lRet) break; } } return 0; } // 清除断点文件 void ClearBreakPoint() { string strBreakPointFileName = Path.Combine(GetBaseDirectory(), "report_breakpoint.xml"); File.Delete(strBreakPointFileName); SetStartButtonStates(); SetDailyReportButtonState(); } // 创建本地存储 // TODO: 中间从服务器复制表的阶段,也应该可以中断,以后可以从断点继续。会出现一个对话框,询问是否继续 private void button_start_createLocalStorage_Click(object sender, EventArgs e) { Task.Factory.StartNew(() => CreateLocalStorage(), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } void CreateLocalStorage() { string strError = ""; try { int nRet = 0; string strBreakPointFileName = Path.Combine(GetBaseDirectory(), "report_breakpoint.xml"); XmlDocument task_dom = new XmlDocument(); try { task_dom.Load(strBreakPointFileName); } catch (FileNotFoundException) { task_dom = null; } catch (Exception ex) { strError = "装载文件 '" + strBreakPointFileName + "' 时出错: " + ex.Message; goto ERROR1; } if (task_dom == null) { // 创建批处理计划 nRet = BuildPlan("*", // * "operlog" out task_dom, out strError); if (nRet == -1) goto ERROR1; task_dom.Save(strBreakPointFileName); } try { nRet = DoPlan(ref task_dom, out strError); } finally { task_dom.Save(strBreakPointFileName); } if (nRet == -1) goto ERROR1; SetStartButtonStates(); SetDailyReportButtonState(); this.Invoke((Action)(() => { MessageBox.Show(this, "处理完成"); })); } catch (Exception ex) { strError = "创建本地存储时出现异常: " + ExceptionUtil.GetDebugText(ex); ReportException(strError, false); goto ERROR1; } return; ERROR1: SetStartButtonStates(); SetDailyReportButtonState(); this.Invoke((Action)(() => { MessageBox.Show(this, strError); })); } void ReportException(string strError, bool bMessageBox = true) { if (bMessageBox) { this.Invoke((Action)(() => { MessageBox.Show(this, strError); })); } if (StringUtil.IsDevelopMode() == false) Program.MainForm.ReportError("dp2circulation 调试信息", strError); } void SetStartButtonStates() { this.Invoke((Action)(() => { string strError = ""; int nRet = 0; string strEndDate = ""; long lIndex = 0; string strState = ""; // 读入断点信息 // return: // -1 出错 // 0 正常 // 1 首次创建尚未完成 nRet = LoadDailyBreakPoint( out strEndDate, out lIndex, out strState, out strError); if (nRet == -1) MessageBox.Show(this, strError); if (strState == "daily") { this.button_start_dailyReplication.Enabled = true; this.button_start_createLocalStorage.Enabled = false; } else if (string.IsNullOrEmpty(strState) == true || strState == "first") { this.button_start_dailyReplication.Enabled = false; this.button_start_createLocalStorage.Enabled = true; } else { this.button_start_dailyReplication.Enabled = false; this.button_start_createLocalStorage.Enabled = false; } if (string.IsNullOrEmpty(strEndDate) == true) this.button_start_dailyReplication.Text = "每日同步"; else this.button_start_dailyReplication.Text = "每日同步 " + strEndDate + "-"; if (strState == "first") { this.button_start_createLocalStorage.Text = "继续创建本地存储"; } else { this.button_start_createLocalStorage.Text = "首次创建本地存储"; } this.checkBox_start_enableFirst.Checked = false; })); } // 写入断点信息 int WriteDailyBreakPoint( LogType logType, string strEndDate, long lIndex, out string strError) { strError = ""; string strFileName = Path.Combine(GetBaseDirectory(), "report_breakpoint.xml"); XmlDocument dom = new XmlDocument(); try { dom.Load(strFileName); } catch (FileNotFoundException) { dom.LoadXml("<root />"); } catch (Exception ex) { strError = "装载文件 '" + strFileName + "' 时出错: " + ex.Message; return -1; } string strPrefix = ""; if ((logType & LogType.AccessLog) != 0) strPrefix = "accessLog_"; DomUtil.SetAttr(dom.DocumentElement, strPrefix + "end_date", strEndDate); DomUtil.SetAttr(dom.DocumentElement, strPrefix + "index", lIndex.ToString()); dom.Save(strFileName); return 0; } // 读入断点信息的版本号 // return: // -1 出错 // 0 文件不存在 // 1 成功 int GetBreakPointVersion( out string version, out string strError) { strError = ""; version = ""; string strFileName = Path.Combine(GetBaseDirectory(), "report_breakpoint.xml"); XmlDocument dom = new XmlDocument(); try { dom.Load(strFileName); } catch (FileNotFoundException) { return 0; } catch (Exception ex) { strError = "装载文件 '" + strFileName + "' 时出错: " + ex.Message; return -1; } version = dom.DocumentElement.GetAttribute("version"); #if NO int nRet = DomUtil.GetDoubleParam(dom.DocumentElement, "version", 0, out version, out strError); if (nRet == -1) return -1; #endif return 1; } // 读入两种断点信息,综合判断 // return: // -1 出错 // 0 正常 // 1 首次创建尚未完成 int LoadDailyBreakPoint( out string strEndDate, out long lIndex, out string strState, out string strError) { strError = ""; strEndDate = ""; lIndex = -1; strState = ""; string strEndDate1 = ""; long lIndex1 = 0; string strState1 = ""; int nRet1 = LoadDailyBreakPoint( LogType.OperLog, out strEndDate1, out lIndex1, out strState1, out strError); if (nRet1 == -1) return -1; string strEndDate2 = ""; long lIndex2 = 0; string strState2 = ""; int nRet2 = LoadDailyBreakPoint( LogType.OperLog, out strEndDate2, out lIndex2, out strState2, out strError); if (nRet2 == -1) return -1; if (strState1 == "first" || strState2 == "first") strState = "first"; else strState = strState1; if (nRet1 == 1 || nRet2 == 1) return 1; // 选小的一个做结束日期 if (string.Compare(strEndDate1, strEndDate2) > 0) { strEndDate = strEndDate2; lIndex = lIndex2; } else { strEndDate = strEndDate1; lIndex = lIndex1; } return 0; } // 读入断点信息 // return: // -1 出错 // 0 正常 // 1 首次创建尚未完成 int LoadDailyBreakPoint( LogType logType, out string strEndDate, out long lIndex, out string strState, out string strError) { strError = ""; strEndDate = ""; strState = ""; lIndex = 0; string strFileName = Path.Combine(GetBaseDirectory(), "report_breakpoint.xml"); XmlDocument dom = new XmlDocument(); try { dom.Load(strFileName); } catch (FileNotFoundException) { dom.LoadXml("<root />"); } catch (Exception ex) { strError = "装载文件 '" + strFileName + "' 时出错: " + ex.Message; return -1; } string strPrefix = ""; if ((logType & LogType.AccessLog) != 0) strPrefix = "accessLog_"; strEndDate = DomUtil.GetAttr(dom.DocumentElement, strPrefix + "end_date"); int nRet = DomUtil.GetIntegerParam(dom.DocumentElement, strPrefix + "index", 0, out lIndex, out strError); if (nRet == -1) return -1; // state 元素中的状态,是首次创建本地缓存后总体的状态,是操作日志和访问日志都复制过来以后,才会设置为 "daily" strState = DomUtil.GetAttr(dom.DocumentElement, "state"); if (strState != "daily") return 1; // 首次创建尚未完成 return 0; } // 获得和当前服务器、用户相关的报表信息本地存储目录 static string GetBaseDirectory() { // 2015/6/20 将数据库文件存储在和每个 dp2library 服务器和用户名相关的目录中 string strDirectory = Path.Combine(Program.MainForm.ServerCfgDir, ReportForm.GetValidPathString(Program.MainForm.GetCurrentUserName())); PathUtil.TryCreateDir(strDirectory); return strDirectory; } public static string GetReportDir() { return Path.Combine(GetBaseDirectory(), "reports"); } string GetOperlogConnectionString() { // return SQLiteUtil.GetConnectionString(Program.MainForm.UserDir, "operlog.bin"); return SQLiteUtil.GetConnectionString(GetBaseDirectory(), "operlog.bin"); } // DoReplication() 过程中使用的 class 属性列表 List<BiblioDbFromInfo> _classFromStyles = new List<BiblioDbFromInfo>(); // 同步 // 注:中途遇到异常(例如 Loader 抛出异常),可能会丢失 INSERT_BATCH 条以内的日志记录写入 operlog 表 // parameters: // strLastDate 处理中断或者结束时返回最后处理过的日期 // last_index 处理或中断返回时最后处理过的位置。以后继续处理的时候可以从这个偏移开始 // return: // -1 出错 // 0 中断 // 1 完成 int DoReplication( string strStartDate, string strEndDate, LogType logType, // long index, out string strLastDate, out long last_index, out string strError) { strError = ""; strLastDate = ""; last_index = -1; // -1 表示尚未处理 bool bUserChanged = false; // strStartDate 里面可能会包含 ":1-100" 这样的附加成分 string strLeft = ""; string strRight = ""; StringUtil.ParseTwoPart(strStartDate, ":", out strLeft, out strRight); strStartDate = strLeft; if (string.IsNullOrEmpty(strStartDate) == true) { strError = "DoReplication() 出错: strStartDate 参数值不应为空"; return -1; } EnableControls(false); this.ChannelDoEvents = !this.InvokeRequired; stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在进行同步 ..."); stop.BeginLoop(); try { List<BiblioDbFromInfo> styles = null; // 获得所有分类号检索途径 style int nRet = GetClassFromStylesFromFile(out styles, out strError); if (nRet == -1) return -1; _classFromStyles = styles; _updateBiblios.Clear(); _updateItems.Clear(); _updateReaders.Clear(); string strWarning = ""; List<string> dates = null; nRet = OperLogLoader.MakeLogFileNames(strStartDate, strEndDate, true, // 是否包含扩展名 ".log" out dates, out strWarning, out strError); if (nRet == -1) return -1; if (dates.Count > 0 && string.IsNullOrEmpty(strRight) == false) { dates[0] = dates[0] + ":" + strRight; } this.Channel.Timeout = new TimeSpan(0, 1, 0); // 一分钟 this._connectionString = GetOperlogConnectionString(); // SQLiteUtil.GetConnectionString(Program.MainForm.UserDir, "operlog.bin"); using (SQLiteConnection connection = new SQLiteConnection(this._connectionString)) { connection.Open(); ProgressEstimate estimate = new ProgressEstimate(); OperLogLoader loader = new OperLogLoader(); loader.Channel = this.Channel; loader.Stop = this.Progress; // loader.owner = this; loader.Estimate = estimate; loader.Dates = dates; loader.Level = 2; // Program.MainForm.OperLogLevel; loader.AutoCache = false; loader.CacheDir = ""; loader.LogType = logType; loader.Prompt -= new MessagePromptEventHandler(loader_Prompt); loader.Prompt += new MessagePromptEventHandler(loader_Prompt); // List<OperLogLine> lines = new List<OperLogLine>(); MultiBuffer buffer = new MultiBuffer(); buffer.Initial(); // OperLogLineBase.MainForm = Program.MainForm; int nRecCount = 0; string strLastItemDate = ""; long lLastItemIndex = -1; foreach (OperLogItem item in loader) { if (stop != null && stop.State != 0) { strError = "用户中断"; return 0; } if (stop != null) stop.SetMessage("正在同步 " + item.Date + " " + item.Index.ToString() + " " + estimate.Text + "..."); if (string.IsNullOrEmpty(item.Xml) == true) goto CONTINUE; XmlDocument dom = new XmlDocument(); try { dom.LoadXml(item.Xml); } catch (Exception ex) { DialogResult result = System.Windows.Forms.DialogResult.No; strError = logType.ToString() + "日志记录 " + item.Date + " " + item.Index.ToString() + " XML 装入 DOM 的时候发生错误: " + ex.Message; string strText = strError; this.Invoke((Action)(() => { result = MessageBox.Show(this, strText + "\r\n\r\n是否跳过此条记录继续处理?", "ReportForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); })); if (result == System.Windows.Forms.DialogResult.No) return -1; // 记入日志,继续处理 this.GetErrorInfoForm().WriteHtml(strError + "\r\n"); continue; } string strOperation = DomUtil.GetElementText(dom.DocumentElement, "operation"); #if NO if (strOperation == "borrow" || strOperation == "return") { OperLogLine line = null; nRet = OperLogLine.Xml2Line(dom, item.Date, item.Index, out line, out strError); if (nRet == -1) return -1; lines.Add(line); if (lines.Count >= INSERT_BATCH) { // 写入 operlog 表一次 nRet = OperLogLine.AppendOperLogLines( connection, lines, true, out strError); if (nRet == -1) return -1; lines.Clear(); // 记忆 strLastDate = item.Date; last_index = item.Index + 1; } } #endif if (strOperation == "setUser") { bUserChanged = true; goto CONTINUE; } else { string strAction = DomUtil.GetElementText(dom.DocumentElement, "action"); OperLogItem current_item = item; if (StringUtil.CompareVersion(Program.MainForm.ServerVersion, "2.74") < 0 && strOperation == "amerce" && (strAction == "amerce" || strAction == "modifyprice")) { // 重新获得当前日志记录,用最详细级别 OperLogItem new_item = loader.LoadOperLogItem(item, 0); if (new_item == null) { strError = "重新获取 OperLogItem 时出错"; return -1; } dom.LoadXml(new_item.Xml); current_item = new_item; } // 在内存中增加一行,关于 operlogXXX 表的信息 nRet = buffer.AddLine( strOperation, dom, current_item.Date, current_item.Index, out strError); if (nRet == -1) return -1; bool bForce = false; if (nRecCount >= 4000) bForce = true; nRet = buffer.WriteToDb(connection, true, bForce, out strError); if (bForce == true) { // 记忆 strLastDate = item.Date; last_index = item.Index + 1; nRecCount = 0; } // 2016/5/22 if (nRet == -1) return -1; nRecCount++; } // 将一条日志记录中的动作兑现到 item reader biblio class_ 表 // return: // -1 出错 // 0 中断 // 1 完成 nRet = ProcessLogRecord( connection, item, dom, out strError); if (nRet == -1) { strError = "同步 " + item.Date + " " + item.Index.ToString() + " 时出错: " + strError; // TODO: 最好有个冻结按钮 DialogResult result = System.Windows.Forms.DialogResult.Cancel; string strText = strError; this.Invoke((Action)(() => { result = AutoCloseMessageBox.Show(this, strText + "\r\n\r\n(点右上角关闭按钮可以中断批处理)", 5000); })); if (result != System.Windows.Forms.DialogResult.OK) return -1; // TODO: 缓存中没有兑现的怎么办? // 记入日志,继续处理 this.GetErrorInfoForm().WriteHtml(strError + "\r\n"); } // lProcessCount++; CONTINUE: // 便于循环外获得这些值 strLastItemDate = item.Date; lLastItemIndex = item.Index + 1; // index = 0; // 第一个日志文件后面的,都从头开始了 } // 缓存中尚未最后兑现的部分 nRet = FlushUpdate( connection, out strError); if (nRet == -1) return -1; // 最后一批 nRet = buffer.WriteToDb(connection, true, true, // false, out strError); if (nRet == -1) return -1; // 记忆 strLastDate = strLastItemDate; last_index = lLastItemIndex; } if (bUserChanged == true) { nRet = DoCreateUserTable(out strError); if (nRet == -1) return -1; } return 1; } catch (Exception ex) { strError = "ReportForm DoReplication() exception: " + ExceptionUtil.GetDebugText(ex); return -1; } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); stop.HideProgress(); EnableControls(true); } } int FlushUpdate( SQLiteConnection connection, out string strError) { strError = ""; int nRet = CommitUpdateBiblios( connection, out strError); if (nRet == -1) { strError = "FlushUpdate() 中 CommitUpdateBiblios() 出错: " + strError; return -1; } nRet = CommitDeleteBiblios( connection, out strError); if (nRet == -1) { strError = "FlushUpdate() 中 CommitDeleteBiblios() 出错: " + strError; return -1; } nRet = CommitUpdateItems( connection, out strError); if (nRet == -1) { strError = "FlushUpdate() 中 CommitUpdateItems() 出错: " + strError; return -1; } nRet = CommitUpdateReaders( connection, out strError); if (nRet == -1) { strError = "FlushUpdate() 中 CommitUpdateReaders() 出错: " + strError; return -1; } return 0; } #region 日志同步 // 将一条日志记录中的动作兑现到 item reader biblio class_ 表 // return: // -1 出错 // 0 中断 // 1 完成 int ProcessLogRecord( SQLiteConnection connection, // DigitalPlatform.LibraryClient.localhost.OperLogInfo info, OperLogItem info, XmlDocument dom, out string strError) { strError = ""; int nRet = 0; #if NO if (string.IsNullOrEmpty(info.Xml) == true) return 0; XmlDocument dom = new XmlDocument(); try { dom.LoadXml(info.Xml); } catch (Exception ex) { strError = "日志记录装载到DOM时出错: " + ex.Message; return -1; } #endif string strOperation = DomUtil.GetElementText(dom.DocumentElement, "operation"); if (strOperation == "setBiblioInfo") { nRet = this.TraceSetBiblioInfo( connection, dom, out strError); } else if (strOperation == "setEntity") { nRet = this.TraceSetEntity( connection, dom, out strError); } else if (strOperation == "setReaderInfo") { nRet = this.TraceSetReaderInfo( connection, dom, out strError); } else if (strOperation == "borrow") { nRet = this.TraceBorrow( connection, dom, out strError); } else if (strOperation == "return") { nRet = this.TraceReturn( connection, dom, out strError); } if (nRet == -1) { string strAction = DomUtil.GetElementText(dom.DocumentElement, "action"); strError = "operation=" + strOperation + ";action=" + strAction + ": " + strError; return -1; } return 1; } int DeleteBiblioRecord( SQLiteConnection connection, string strBiblioRecPath, bool bDeleteBiblio, bool bDeleteSubrecord, out string strError) { strError = ""; int nRet = 0; // 把前面积累的关于修改书目记录的请求全部兑现了 if (this._updateBiblios.Count > 0) { nRet = CommitUpdateBiblios( connection, out strError); if (nRet == -1) { strError = "DeleteBiblioRecord() 中 CommitUpdateBiblios() 出错: " + strError; return -1; } } if (bDeleteBiblio == false && bDeleteSubrecord == false) { return 0; } // 把请求放入队列 UpdateBiblio update = new UpdateBiblio(); update.BiblioRecPath = strBiblioRecPath; update.DeleteBiblio = bDeleteBiblio; update.DeleteSubrecord = bDeleteSubrecord; // update.BiblioXml = strBiblioXml; _deleteBiblios.Add(update); // if (this._updateBiblios.Count >= UPDATE_BIBLIOS_BATCHSIZE) // BUG if (this._deleteBiblios.Count >= DELETE_BIBLIOS_BATCHSIZE) { nRet = CommitDeleteBiblios( connection, out strError); if (nRet == -1) { strError = "UpdateBiblioRecord() 中 CommitUpdateBiblios() 出错: " + strError; return -1; } } return 1; } int CommitDeleteBiblios( SQLiteConnection connection, out string strError) { strError = ""; //int nRet = 0; if (this._deleteBiblios.Count == 0) return 0; Debug.WriteLine("CommitDeleteBiblios() _deleteBiblios.Count=" + _deleteBiblios.Count); #if NO List<BiblioDbFromInfo> styles = null; // 获得所有分类号检索途径 style nRet = GetClassFromStyles(out styles, out strError); if (nRet == -1) return -1; #endif Debug.Assert(this._classFromStyles != null, ""); using (SQLiteTransaction mytransaction = connection.BeginTransaction()) { using (SQLiteCommand command = new SQLiteCommand("", connection)) { StringBuilder text = new StringBuilder(4096); int i = 0; foreach (UpdateBiblio update in this._deleteBiblios) { string strBiblioRecPath = update.BiblioRecPath; Debug.Assert(string.IsNullOrEmpty(strBiblioRecPath) == false, ""); if (update.DeleteBiblio) { foreach (BiblioDbFromInfo style in this._classFromStyles) { // 删除 class 记录 text.Append("delete from class_" + style.Style + " where bibliorecpath = @bibliorecpath" + i.ToString() + " ;"); } } SQLiteUtil.SetParameter(command, "@bibliorecpath" + i.ToString(), strBiblioRecPath); if (update.DeleteBiblio) { // 删除 biblio 记录 text.Append("delete from biblio where bibliorecpath = @bibliorecpath" + i.ToString() + " ;"); } if (update.DeleteSubrecord) { // 删除 item 记录 text.Append("delete from item where bibliorecpath = @bibliorecpath" + i.ToString() + " ;"); #if NO // 删除 order 记录 text.Append("delete from order where bibliorecpath = @bibliorecpath" + i.ToString() + " ;"); // 删除 issue 记录 text.Append("delete from issue where bibliorecpath = @bibliorecpath" + i.ToString() + " ;"); // 删除 comment 记录 text.Append("delete from comment where bibliorecpath = @bibliorecpath" + i.ToString() + " ;"); #endif } i++; } if (text.Length > 0) { command.CommandText = text.ToString(); int nCount = command.ExecuteNonQuery(); } } mytransaction.Commit(); } this._deleteBiblios.Clear(); return 0; } const int DELETE_BIBLIOS_BATCHSIZE = 10; List<UpdateBiblio> _deleteBiblios = new List<UpdateBiblio>(); // 应当是连续的 Update 操作,才能缓存。中间有 Delete 操作,就要把前面的缓存队先后,立即执行 Delete class UpdateBiblio { public string BiblioRecPath = ""; public string BiblioXml = ""; // 是否删除书目记录部分 public bool DeleteBiblio = true; // 是否删除下级记录 public bool DeleteSubrecord = true; public string Summary = ""; // [out] public string KeysXml = ""; // [out] } const int UPDATE_BIBLIOS_BATCHSIZE = 10; List<UpdateBiblio> _updateBiblios = new List<UpdateBiblio>(); // 更新 biblio 表 和 class_xxx 表中的行 int UpdateBiblioRecord( SQLiteConnection connection, string strBiblioRecPath, string strBiblioXml, out string strError) { strError = ""; int nRet = 0; string strDbName = Global.GetDbName(strBiblioRecPath); if (Program.MainForm.IsBiblioDbName(strDbName) == false) return 0; // 把前面积累的关于删除书目记录的请求全部兑现了 if (this._deleteBiblios.Count > 0) { nRet = CommitDeleteBiblios( connection, out strError); if (nRet == -1) { strError = "UpdateBiblioRecord() 中 CommitDeleteBiblios() 出错: " + strError; return -1; } } // 把请求放入队列 UpdateBiblio update = new UpdateBiblio(); update.BiblioRecPath = strBiblioRecPath; update.DeleteBiblio = false; // 没有用到 update.DeleteSubrecord = false; // 没有用到 // update.BiblioXml = strBiblioXml; _updateBiblios.Add(update); if (this._updateBiblios.Count >= UPDATE_BIBLIOS_BATCHSIZE) { nRet = CommitUpdateBiblios( connection, out strError); if (nRet == -1) { strError = "UpdateBiblioRecord() 中 CommitUpdateBiblios() 出错: " + strError; return -1; } } return 0; } int CommitUpdateBiblios( SQLiteConnection connection, out string strError) { strError = ""; int nRet = 0; if (this._updateBiblios.Count == 0) return 0; Debug.WriteLine("CommitUpdateBiblios() _updateBiblios.Count=" + _updateBiblios.Count); List<UpdateBiblio> temp_updates = new List<UpdateBiblio>(); List<string> recpaths = new List<string>(); StringBuilder text = new StringBuilder(4096); int i = 0; foreach (UpdateBiblio update in _updateBiblios) { temp_updates.Add(update); recpaths.Add(update.BiblioRecPath); #if NO if (text.Length > 0) text.Append("<!-->"); text.Append(update.BiblioXml); if (text.Length > 500 * 1024 || (text.Length > 0 && i == _updateBiblios.Count - 1)) { // 调用一次 API 获得检索点和书目摘要 string[] formats = new string[2]; formats[0] = "keys"; formats[1] = "summary"; string[] results = null; byte[] timestamp = null; REDO: long lRet = Channel.GetBiblioInfos( Progress, "@path-list:" + StringUtil.MakePathList(recpaths), text.ToString(), formats, out results, out timestamp, out strError); if (lRet == -1) { DialogResult result = MessageBox.Show(this, "获取书目记录信息 (" + StringUtil.MakePathList(recpaths) + ") 的操作发生错误: " + strError + "\r\n\r\n是否重试操作?\r\n\r\n(是: 重试; 取消: 停止操作)", "ReportForm", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (result == DialogResult.OK) goto REDO; if (result == DialogResult.Cancel) return -1; } if (results == null) { strError = "results == null "; return -1; } if (results.Length < temp_updates.Count * 2) { strError = "results.Length " + results.Length + " 不正确,应该为 " + temp_updates.Count * 2; return -1; } for (int j = 0; j < temp_updates.Count; j++) { UpdateBiblio temp_update = temp_updates[j]; temp_update.KeysXml = results[j * 2]; temp_update.Summary = results[j * 2 + 1]; } temp_updates.Clear(); recpaths.Clear(); text.Clear(); } #endif if (recpaths.Count >= 100 || (recpaths.Count > 0 && i >= _updateBiblios.Count - 1)) { // 调用一次 API 获得检索点和书目摘要 string[] formats = new string[2]; formats[0] = "keys"; formats[1] = "summary"; string[] results = null; byte[] timestamp = null; REDO: long lRet = Channel.GetBiblioInfos( Progress, "@path-list:" + StringUtil.MakePathList(recpaths), text.ToString(), formats, out results, out timestamp, out strError); if (lRet == -1) { DialogResult result = DialogResult.Cancel; string strText = strError; this.Invoke((Action)(() => { result = MessageBox.Show(this, "获取书目记录信息 (" + StringUtil.MakePathList(recpaths) + ") 的操作发生错误: " + strText + "\r\n\r\n是否重试操作?\r\n\r\n(是: 重试; 取消: 停止操作)", "ReportForm", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); })); if (result == DialogResult.OK) goto REDO; if (result == DialogResult.Cancel) return -1; } if (lRet > 0) { if (results == null) { strError = "results == null "; return -1; } if (results.Length < temp_updates.Count * 2) { strError = "results.Length " + results.Length + " 不正确,应该为 " + temp_updates.Count * 2; return -1; } for (int j = 0; j < temp_updates.Count; j++) { UpdateBiblio temp_update = temp_updates[j]; temp_update.KeysXml = results[j * 2]; temp_update.Summary = results[j * 2 + 1]; } } temp_updates.Clear(); recpaths.Clear(); text.Clear(); } i++; } Debug.Assert(text.Length == 0, ""); Debug.Assert(recpaths.Count == 0, ""); // 更新 SQL 表 nRet = CommitUpdateBiblioRecord( connection, this._updateBiblios, out strError); if (nRet == -1) return -1; this._updateBiblios.Clear(); return 1; } // 更新 SQL 表 int CommitUpdateBiblioRecord( SQLiteConnection connection, List<UpdateBiblio> updates, out string strError) { strError = ""; Debug.WriteLine("CommitUpdateBiblioRecord() updates.Count=" + updates.Count); StringBuilder command_text = new StringBuilder(4096); using (SQLiteTransaction mytransaction = connection.BeginTransaction()) { using (SQLiteCommand command = new SQLiteCommand("", connection)) { int i = 0; foreach (UpdateBiblio update in updates) { if (string.IsNullOrEmpty(update.Summary) == true && string.IsNullOrEmpty(update.BiblioRecPath) == true) continue; bool bBiblioRecPathParamSetted = false; if (string.IsNullOrEmpty(update.Summary) == false) { // 把书目摘要写入 biblio 表 command_text.Append("insert or replace into biblio values (@bibliorecpath" + i + ", @summary" + i + ") ;"); SQLiteUtil.SetParameter(command, "@bibliorecpath" + i, update.BiblioRecPath); bBiblioRecPathParamSetted = true; SQLiteUtil.SetParameter(command, "@summary" + i, update.Summary); } // *** 取得分类号 keys if (_classFromStyles.Count == 0) goto CONTINUE; if (string.IsNullOrEmpty(update.KeysXml) == true) goto CONTINUE; XmlDocument dom = new XmlDocument(); try { dom.LoadXml(update.KeysXml); } catch (Exception ex) { strError = "update.KeysXml XML 装入 DOM 时出错: " + ex.Message; return -1; } int j = 0; foreach (BiblioDbFromInfo style in _classFromStyles) { XmlNodeList nodes = dom.DocumentElement.SelectNodes("k[@f='" + style.Caption + "']"); List<string> keys = new List<string>(); foreach (XmlNode node in nodes) { keys.Add(DomUtil.GetAttr(node, "k")); } command_text.Append("delete from class_" + style.Style + " where bibliorecpath = @bibliorecpath" + i + " ;"); if (bBiblioRecPathParamSetted == false) { SQLiteUtil.SetParameter(command, "@bibliorecpath" + i, update.BiblioRecPath); bBiblioRecPathParamSetted = true; } /* SQLiteUtil.SetParameter(command, "@bibliorecpath", update.BiblioRecPath); * */ foreach (string key in keys) { // 把分类号写入分类号表 command_text.Append("insert into class_" + style.Style + " values (@bibliorecpath" + i + ", @class_" + i + "_" + j + ") ;"); SQLiteUtil.SetParameter(command, "@class_" + i + "_" + j, key); j++; } } CONTINUE: i++; } try { command.CommandText = command_text.ToString(); int nCount = command.ExecuteNonQuery(); } catch (Exception ex) { strError = "更新 biblio 表时出错.\r\n" + ex.Message + "\r\n" + "SQL 命令:\r\n" + command_text.ToString(); return -1; } } mytransaction.Commit(); } return 0; } // Return() API 恢复动作 /* <root> <operation>return</operation> 操作类型 <action>return</action> 动作。有 return/lost/inventory/read/boxing 几种。恢复动作目前仅恢复 return 和 lost 两种,其余会忽略 <itemBarcode>0000001</itemBarcode> 册条码号 <readerBarcode>R0000002</readerBarcode> 读者证条码号 <operator>test</operator> 操作者 <operTime>Fri, 08 Dec 2006 04:17:45 GMT</operTime> 操作时间 <overdues>...</overdues> 超期信息 通常内容为一个字符串,为一个<overdue>元素XML文本片断 <confirmItemRecPath>...</confirmItemRecPath> 辅助判断用的册记录路径 <readerRecord recPath='...'>...</readerRecord> 最新读者记录 <itemRecord recPath='...'>...</itemRecord> 最新册记录 </root> * */ public int TraceReturn( SQLiteConnection connection, XmlDocument domLog, out string strError) { strError = ""; string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); if (strAction != "return" && strAction != "lost") return 0; // 其余 inventory/read/boxing 动作并不会改变任何册记录,所以这里返回了 //long lRet = 0; int nRet = 0; string strReaderBarcode = DomUtil.GetElementText(domLog.DocumentElement, "readerBarcode"); if (String.IsNullOrEmpty(strReaderBarcode) == true) { strError = "<readerBarcode>元素值为空"; return -1; } // 读入册记录 string strConfirmItemRecPath = DomUtil.GetElementText(domLog.DocumentElement, "confirmItemRecPath"); string strItemBarcode = DomUtil.GetElementText(domLog.DocumentElement, "itemBarcode"); if (String.IsNullOrEmpty(strItemBarcode) == true) { strError = "<strItemBarcode>元素值为空"; return -1; } ItemLine line = new ItemLine(); // line.Full = false; line.Level = 1; line.ItemBarcode = strItemBarcode; line.Borrower = ""; line.BorrowTime = ""; line.BorrowPeriod = ""; line.ReturningTime = ""; line.ItemRecPath = strConfirmItemRecPath; this._updateItems.Add(line); if (this._updateItems.Count >= UPDATE_ITEMS_BATCHSIZE) { nRet = CommitUpdateItems( connection, out strError); if (nRet == -1) return -1; } return 0; } // Borrow() API 恢复动作 /* <root> <operation>borrow</operation> 操作类型 <readerBarcode>R0000002</readerBarcode> 读者证条码号 <itemBarcode>0000001</itemBarcode> 册条码号 <borrowDate>Fri, 08 Dec 2006 04:17:31 GMT</borrowDate> 借阅日期 <borrowPeriod>30day</borrowPeriod> 借阅期限 <no>0</no> 续借次数。0为首次普通借阅,1开始为续借 <operator>test</operator> 操作者 <operTime>Fri, 08 Dec 2006 04:17:31 GMT</operTime> 操作时间 <confirmItemRecPath>...</confirmItemRecPath> 辅助判断用的册记录路径 <readerRecord recPath='...'>...</readerRecord> 最新读者记录 <itemRecord recPath='...'>...</itemRecord> 最新册记录 </root> * */ public int TraceBorrow( SQLiteConnection connection, XmlDocument domLog, out string strError) { strError = ""; //long lRet = 0; int nRet = 0; string strReaderBarcode = DomUtil.GetElementText(domLog.DocumentElement, "readerBarcode"); if (String.IsNullOrEmpty(strReaderBarcode) == true) { strError = "<readerBarcode>元素值为空"; return -1; } // 读入册记录 string strConfirmItemRecPath = DomUtil.GetElementText(domLog.DocumentElement, "confirmItemRecPath"); string strItemBarcode = DomUtil.GetElementText(domLog.DocumentElement, "itemBarcode"); if (String.IsNullOrEmpty(strItemBarcode) == true) { strError = "<strItemBarcode>元素值为空"; return -1; } string strBorrowDate = SQLiteUtil.GetLocalTime(DomUtil.GetElementText(domLog.DocumentElement, "borrowDate")); string strBorrowPeriod = DomUtil.GetElementText(domLog.DocumentElement, "borrowPeriod"); //string strReturningDate = ItemLine.GetLocalTime(DomUtil.GetElementText(domLog.DocumentElement, // "returningDate")); string strReturningTime = ""; if (string.IsNullOrEmpty(strBorrowDate) == false) { // parameters: // strBorrowTime 借阅起点时间。u 格式 // strReturningTime 返回应还时间。 u 格式 nRet = AmerceOperLogLine.BuildReturingTimeString(strBorrowDate, strBorrowPeriod, out strReturningTime, out strError); if (nRet == -1) { strReturningTime = ""; } } else strReturningTime = ""; ItemLine line = new ItemLine(); // line.Full = false; line.Level = 1; line.ItemBarcode = strItemBarcode; line.Borrower = strReaderBarcode; line.BorrowTime = strBorrowDate; line.BorrowPeriod = strBorrowPeriod; line.ReturningTime = strReturningTime; line.ItemRecPath = strConfirmItemRecPath; this._updateItems.Add(line); if (this._updateItems.Count >= UPDATE_ITEMS_BATCHSIZE) { nRet = CommitUpdateItems( connection, out strError); if (nRet == -1) return -1; } return 0; } // SetReaderInfo() API 恢复动作 /* <root> <operation>setReaderInfo</operation> 操作类型 <action>...</action> 具体动作。有new change delete move 4种 <record recPath='...'>...</record> 新记录 <oldRecord recPath='...'>...</oldRecord> 被覆盖或者删除的记录 动作为change和delete时具备此元素 <changedEntityRecord itemBarcode='...' recPath='...' oldBorrower='...' newBorrower='...' /> 若干个元素。表示连带发生修改的册记录 <operator>test</operator> 操作者 <operTime>Fri, 08 Dec 2006 09:01:38 GMT</operTime> 操作时间 </root> 注: new 的时候只有<record>元素,delete的时候只有<oldRecord>元素,change的时候两者都有 * */ public int TraceSetReaderInfo( SQLiteConnection connection, XmlDocument domLog, out string strError) { strError = ""; //long lRet = 0; int nRet = 0; string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); if (strAction == "new" || strAction == "change" || strAction == "move") { XmlNode node = null; string strRecord = DomUtil.GetElementText(domLog.DocumentElement, "record", out node); if (node == null) { strError = "日志记录中缺<record>元素"; return -1; } string strNewRecPath = DomUtil.GetAttr(node, "recPath"); string strOldRecord = ""; string strOldRecPath = ""; if (strAction == "move") { strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } strOldRecPath = DomUtil.GetAttr(node, "recPath"); if (string.IsNullOrEmpty(strOldRecPath) == true) { strError = "日志记录中<oldRecord>元素内缺recPath属性值"; return -1; } // 如果移动过程中没有修改,则要用旧的记录内容写入目标 if (string.IsNullOrEmpty(strRecord) == true) strRecord = strOldRecord; } // 在 SQL reader 库中写入一条读者记录 nRet = WriteReaderRecord(connection, strNewRecPath, strRecord, out strError); if (nRet == -1) { strError = "写入读者记录 '" + strNewRecPath + "' 时发生错误: " + strError; return -1; } // 2015/9/11 XmlNodeList nodes = domLog.DocumentElement.SelectNodes("changedEntityRecord"); foreach (XmlElement item in nodes) { string strItemBarcode = item.GetAttribute("itemBarcode"); string strItemRecPath = item.GetAttribute("recPath"); string strOldReaderBarcode = item.GetAttribute("oldBorrower"); string strNewReaderBarcode = item.GetAttribute("newBorrower"); nRet = TraceChangeBorrower( connection, strItemBarcode, strItemRecPath, strNewReaderBarcode, out strError); if (nRet == -1) { strError = "修改册记录 '" + strItemRecPath + "' 的 borrower 字段时发生错误: " + strError; return -1; } } if (strAction == "move") { // 兑现缓存 nRet = CommitUpdateReaders( connection, out strError); if (nRet == -1) return -1; // 删除读者记录 nRet = ReaderLine.DeleteReaderLine( connection, strOldRecPath, out strError); if (nRet == -1) return -1; } } else if (strAction == "delete") { XmlNode node = null; string strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } string strRecPath = DomUtil.GetAttr(node, "recPath"); // 兑现缓存 nRet = CommitUpdateReaders( connection, out strError); if (nRet == -1) return -1; // 删除读者记录 nRet = ReaderLine.DeleteReaderLine( connection, strRecPath, out strError); if (nRet == -1) return -1; } else { strError = "无法识别的<action>内容 '" + strAction + "'"; return -1; } return 0; } public int TraceChangeBorrower( SQLiteConnection connection, string strItemBarcode, string strItemRecPath, string strNewBorrower, out string strError) { strError = ""; //long lRet = 0; int nRet = 0; if (String.IsNullOrEmpty(strItemBarcode) == true) { strError = "strItemBarcode 参数不应为空"; return -1; } ItemLine line = new ItemLine(); // line.Full = false; line.Level = 2; line.ItemBarcode = strItemBarcode; line.Borrower = strNewBorrower; line.ItemRecPath = strItemRecPath; this._updateItems.Add(line); if (this._updateItems.Count >= UPDATE_ITEMS_BATCHSIZE) { nRet = CommitUpdateItems( connection, out strError); if (nRet == -1) return -1; } return 0; } // SetEntities() API 恢复动作 /* 日志记录格式 <root> <operation>setEntity</operation> 操作类型 <action>new</action> 具体动作。有new change delete 3种 <style>...</style> 风格。有force nocheckdup noeventlog 3种 <record recPath='中文图书实体/3'><root><parent>2</parent><barcode>0000003</barcode><state>状态2</state><location>阅览室</location><price></price><bookType>教学参考</bookType><registerNo></registerNo><comment>test</comment><mergeComment></mergeComment><batchNo>111</batchNo><borrower></borrower><borrowDate></borrowDate><borrowPeriod></borrowPeriod></root></record> 记录体 <oldRecord recPath='中文图书实体/3'>...</oldRecord> 被覆盖或者删除的记录 动作为change和delete时具备此元素 <operator>test</operator> 操作者 <operTime>Fri, 08 Dec 2006 08:41:46 GMT</operTime> 操作时间 </root> 注:1) 当<action>为delete时,没有<record>元素。为new时,没有<oldRecord>元素。 2) <record>中的内容, 涉及到流通的<borrower><borrowDate><borrowPeriod>等, 在日志恢复阶段, 都应当无效, 这几个内容应当从当前位置库中记录获取, 和<record>中其他内容合并后, 再写入数据库 3) 一次SetEntities()API调用, 可能创建多条日志记录。 * */ public int TraceSetEntity( SQLiteConnection connection, XmlDocument domLog, out string strError) { strError = ""; //long lRet = 0; int nRet = 0; string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); if (strAction == "new" || strAction == "change" || strAction == "move") { XmlNode node = null; string strRecord = DomUtil.GetElementText(domLog.DocumentElement, "record", out node); if (node == null) { #if NO strError = "日志记录中缺<record>元素"; return -1; #endif // 改为进行删除操作 strAction = "delete"; goto TRY_DELETE; } string strNewRecPath = DomUtil.GetAttr(node, "recPath"); // string strOldRecord = ""; string strOldRecPath = ""; if (strAction == "move") { strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } strOldRecPath = DomUtil.GetAttr(node, "recPath"); } string strCreateOperTime = ""; if (strAction == "new") strCreateOperTime = DomUtil.GetElementText(domLog.DocumentElement, "operTime"); // 在 SQL item 库中写入一条册记录 nRet = WriteItemRecord(connection, strNewRecPath, strRecord, strCreateOperTime, out strError); if (nRet == -1) { strError = "写入册记录 '" + strNewRecPath + "' 时发生错误: " + strError; return -1; } if (strAction == "move") { // 兑现前面的缓存 nRet = CommitUpdateItems( connection, out strError); if (nRet == -1) return -1; // 删除册记录 nRet = ItemLine.DeleteItemLine( connection, strOldRecPath, out strError); if (nRet == -1) return -1; } return 0; } TRY_DELETE: if (strAction == "delete") { XmlNode node = null; string strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } string strRecPath = DomUtil.GetAttr(node, "recPath"); // 兑现前面的缓存 nRet = CommitUpdateItems( connection, out strError); if (nRet == -1) return -1; // 删除册记录 nRet = ItemLine.DeleteItemLine( connection, strRecPath, out strError); if (nRet == -1) return -1; return 0; } strError = "无法识别的<action>内容 '" + strAction + "'"; return -1; } // SetBiblioInfo() API 或 CopyBiblioInfo() API 的恢复动作 // 函数内,使用return -1;还是goto ERROR1; 要看错误发生的时候,是否还有价值继续探索SnapShot重试。如果是,就用后者。 /* <root> <operation>setBiblioInfo</operation> <action>...</action> 具体动作 有 new/change/delete/onlydeletebiblio/onlydeletesubrecord 和 onlycopybiblio/onlymovebiblio/copy/move <record recPath='中文图书/3'>...</record> 记录体 动作为new/change/ *move* / *copy* 时具有此元素(即delete时没有此元素) <oldRecord recPath='中文图书/3'>...</oldRecord> 被覆盖、删除或者移动的记录 动作为change/ *delete* / *move* / *copy* 时具备此元素 <deletedEntityRecords> 被删除的实体记录(容器)。只有当<action>为delete时才有这个元素。 <record recPath='中文图书实体/100'>...</record> 这个元素可以重复。注意元素内文本内容目前为空。 ... </deletedEntityRecords> <copyEntityRecords> 被复制的实体记录(容器)。只有当<action>为*copy*时才有这个元素。 <record recPath='中文图书实体/100' targetRecPath='中文图书实体/110'>...</record> 这个元素可以重复。注意元素内文本内容目前为空。recPath属性为源记录路径,targetRecPath为目标记录路径 ... </copyEntityRecords> <moveEntityRecords> 被移动的实体记录(容器)。只有当<action>为*move*时才有这个元素。 <record recPath='中文图书实体/100' targetRecPath='中文图书实体/110'>...</record> 这个元素可以重复。注意元素内文本内容目前为空。recPath属性为源记录路径,targetRecPath为目标记录路径 ... </moveEntityRecords> <copyOrderRecords /> <moveOrderRecords /> <copyIssueRecords /> <moveIssueRecords /> <copyCommentRecords /> <moveCommentRecords /> <operator>test</operator> <operTime>Fri, 08 Dec 2006 10:12:20 GMT</operTime> </root> 逻辑恢复delete操作的时候,检索出全部下属的实体记录删除。 快照恢复的时候,可以根据operlogdom直接删除记录了path的那些实体记录 * */ public int TraceSetBiblioInfo( SQLiteConnection connection, XmlDocument domLog, out string strError) { strError = ""; //long lRet = 0; int nRet = 0; string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); if (strAction == "new" || strAction == "change") { XmlNode node = null; string strRecord = DomUtil.GetElementText(domLog.DocumentElement, "record", out node); if (node == null) { strError = "日志记录中缺<record>元素"; return -1; } string strRecPath = DomUtil.GetAttr(node, "recPath"); if (string.IsNullOrEmpty(strRecPath) == true) return 0; // 轮空 string strTimestamp = DomUtil.GetAttr(node, "timestamp"); // 把书目摘要写入 biblio 表 // 把分类号写入若干分类号表 nRet = UpdateBiblioRecord( connection, strRecPath, strRecord, out strError); if (nRet == -1) return -1; // 在 biblio 表中写入 summary 为空或者特殊标志的记录,最后按照标记全部重新获得? } else if (strAction == "onlymovebiblio" || strAction == "onlycopybiblio" || strAction == "move" || strAction == "copy") { XmlNode node = null; string strTargetRecord = DomUtil.GetElementText(domLog.DocumentElement, "record", out node); if (node == null) { strError = "日志记录中缺<record>元素"; return -1; } string strTargetRecPath = DomUtil.GetAttr(node, "recPath"); if (string.IsNullOrEmpty(strTargetRecPath) == true) return 0; string strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } string strOldRecPath = DomUtil.GetAttr(node, "recPath"); bool bOldExist = DomUtil.GetBooleanParam(node, "exist", true); string strMergeStyle = DomUtil.GetElementText(domLog.DocumentElement, "mergeStyle"); #if NO bool bSourceExist = true; // 观察源记录是否存在 if (string.IsNullOrEmpty(strOldRecPath) == true) bSourceExist = false; else { } if (bSourceExist == true && string.IsNullOrEmpty(strTargetRecPath) == false) { // 注: 实际上是从本地复制到本地 // 复制书目记录 lRet = channel.DoCopyRecord(strOldRecPath, strTargetRecPath, strAction == "onlymovebiblio" ? true : false, // bDeleteSourceRecord out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "DoCopyRecord() error :" + strError; goto ERROR1; } } // 准备需要写入目标位置的记录 if (bSourceExist == false) { if (String.IsNullOrEmpty(strTargetRecord) == true) { if (String.IsNullOrEmpty(strOldRecord) == true) { strError = "源记录 '" + strOldRecPath + "' 不存在,并且<record>元素无文本内容,这时<oldRecord>元素也无文本内容,无法获得要写入的记录内容"; return -1; } strTargetRecord = strOldRecord; } } #endif // 如果目标记录没有记载,就尽量用源记录 if (String.IsNullOrEmpty(strTargetRecord) == true) { if (String.IsNullOrEmpty(strOldRecord) == true) { if (bOldExist == true) { strError = "源记录 '" + strOldRecPath + "' 不存在,并且<record>元素无文本内容,这时<oldRecord>元素也无文本内容,无法获得要写入的记录内容"; return -1; } } else strTargetRecord = strOldRecord; } // 如果有“新记录”内容 if (string.IsNullOrEmpty(strTargetRecPath) == false && String.IsNullOrEmpty(strTargetRecord) == false) { // 写入新的书目记录 nRet = UpdateBiblioRecord( connection, strTargetRecPath, strTargetRecord, out strError); if (nRet == -1) return -1; } // 复制或者移动下级子记录 if (strAction == "move" || strAction == "copy") { nRet = CopySubRecords( connection, domLog, strAction, // string strSourceBiblioRecPath, strTargetRecPath, out strError); if (nRet == -1) return -1; } if (strAction == "move" || strAction == "onlymovebiblio") { // 删除旧的书目记录 nRet = DeleteBiblioRecord( connection, strOldRecPath, true, true, out strError); if (nRet == -1) return -1; } } else if (strAction == "delete" || strAction == "onlydeletebiblio" || strAction == "onlydeletesubrecord") { XmlNode node = null; string strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } string strRecPath = DomUtil.GetAttr(node, "recPath"); if (string.IsNullOrEmpty(strRecPath) == false) { // 删除书目记录 nRet = DeleteBiblioRecord( connection, strRecPath, strAction == "delete" || strAction == "onlydeletebiblio" ? true : false, strAction == "delete" || strAction == "onlydeletesubrecord" ? true : false, out strError); if (nRet == -1) return -1; } } return 0; } // TODO: 需要扩展为也能复制 order issue comment 记录 int CopySubRecords( SQLiteConnection connection, XmlDocument dom, string strAction, // string strSourceBiblioRecPath, string strTargetBiblioRecPath, out string strError) { strError = ""; int nRet = 0; if (dom == null || dom.DocumentElement == null) return 0; string strElement = ""; if (strAction == "move") strElement = "moveEntityRecords"; else if (strAction == "copy") strElement = "copyEntityRecords"; XmlNodeList nodes = dom.DocumentElement.SelectNodes(strElement + "/record"); if (nodes.Count == 0) return 0; nRet = CommitUpdateBiblios( connection, out strError); if (nRet == -1) { strError = "CopySubRecords() 中 CommitUpdateBiblios() 出错: " + strError; return -1; } nRet = CommitDeleteBiblios( connection, out strError); if (nRet == -1) { strError = "CopySubRecords() 中 CommitDeleteBiblios() 出错: " + strError; return -1; } StringBuilder text = new StringBuilder(4096); using (SQLiteTransaction mytransaction = connection.BeginTransaction()) { int i = 0; using (SQLiteCommand command = new SQLiteCommand("", connection)) { SQLiteUtil.SetParameter(command, "@t_bibliorecpath", strTargetBiblioRecPath); Debug.WriteLine("CopySubRecords() nodes.Count=" + nodes.Count); foreach (XmlNode node in nodes) { string strSourceRecPath = DomUtil.GetAttr(node, "recPath"); string strTargetRecPath = DomUtil.GetAttr(node, "targetRecPath"); if (strAction == "copy") { string strNewBarcode = DomUtil.GetAttr(node, "newBarocde"); // TODO: 目标位置实体记录已经存在怎么办 ? // 目标册记录的 barcode 字段要修改为空 text.Append("insert or replace into item (itemrecpath, itembarcode, location, accessno, bibliorecpath) "); text.Append("select @t_itemrecpath" + i + " as itemrecpath, @newbarcode" + i + " as itembarcode, location, accessno, @t_bibliorecpath as bibliorecpath from item where itemrecpath = @s_itemrecpath" + i + " ; "); SQLiteUtil.SetParameter(command, "@newbarcode" + i, strNewBarcode); } else { // *** 如果目标位置有记录,而源位置没有记录,应该是直接在目标记录上修改 // 确保源位置有记录 text.Append("insert or ignore into item (itemrecpath, itembarcode, location, accessno, bibliorecpath) "); text.Append("select @s_itemrecpath" + i + " as itemrecpath, itembarcode, location, accessno, @t_bibliorecpath as bibliorecpath from item where itemrecpath = @t_itemrecpath" + i + " ; "); // 如果目标位置已经有记录,先删除 text.Append("delete from item where itemrecpath = @t_itemrecpath" + i + " ;"); // 等于是修改 item 表的 itemrecpath 字段内容 text.Append("update item SET itemrecpath = @t_itemrecpath" + i + " , bibliorecpath = @t_bibliorecpath where itemrecpath=@s_itemrecpath" + i + " ;"); } SQLiteUtil.SetParameter(command, "@t_itemrecpath" + i, strTargetRecPath); SQLiteUtil.SetParameter(command, "@s_itemrecpath" + i, strSourceRecPath); i++; } command.CommandText = text.ToString(); int nCount = command.ExecuteNonQuery(); } mytransaction.Commit(); } return 0; } const int UPDATE_ITEMS_BATCHSIZE = 10; List<ItemLine> _updateItems = new List<ItemLine>(); // 在 SQL item 库中写入一条册记录 // parameters: // strLogCreateTime 日志操作记载的创建时间。不是创建动作的其他时间,不要放在这里 int WriteItemRecord(SQLiteConnection connection, string strItemRecPath, string strItemXml, string strLogCreateTime, out string strError) { strError = ""; XmlDocument dom = new XmlDocument(); try { dom.LoadXml(strItemXml); } catch (Exception ex) { strError = "XML 装入 DOM 出错: " + ex.Message; return -1; } string strParentID = DomUtil.GetElementText(dom.DocumentElement, "parent"); // 根据 册/订购/期/评注 记录路径和 parentid 构造所从属的书目记录路径 string strBiblioRecPath = Program.MainForm.BuildBiblioRecPath("item", strItemRecPath, strParentID); if (string.IsNullOrEmpty(strBiblioRecPath) == true) { strError = "根据册记录路径 '" + strItemRecPath + "' 和 parentid '" + strParentID + "' 构造书目记录路径出错"; return 0; } ItemLine line = null; // XML 记录变换为 SQL 记录 int nRet = ItemLine.Xml2Line(dom, strItemRecPath, strBiblioRecPath, strLogCreateTime, out line, out strError); if (nRet == -1) return -1; this._updateItems.Add(line); if (this._updateItems.Count >= UPDATE_ITEMS_BATCHSIZE) { nRet = CommitUpdateItems( connection, out strError); if (nRet == -1) return -1; } return 0; } int CommitUpdateItems( SQLiteConnection connection, out string strError) { strError = ""; int nRet = 0; if (this._updateItems.Count == 0) return 0; Debug.WriteLine("CommitUpdateItems() _updateItems.Count=" + _updateItems.Count); // 插入一批册记录 nRet = ItemLine.AppendItemLines( connection, _updateItems, true, out strError); if (nRet == -1) return -1; this._updateItems.Clear(); return 0; } const int UPDATE_READERS_BATCHSIZE = 10; List<ReaderLine> _updateReaders = new List<ReaderLine>(); // 在 SQL reader 库中写入一条读者记录 int WriteReaderRecord(SQLiteConnection connection, string strReaderRecPath, string strReaderXml, out string strError) { strError = ""; if (string.IsNullOrEmpty(strReaderRecPath) == true) return 0; XmlDocument dom = new XmlDocument(); try { dom.LoadXml(strReaderXml); } catch (Exception ex) { strError = "WriteReaderRecord XML 装入 DOM 出错: " + ex.Message; return -1; } // 根据读者库名,得到馆代码 string strReaderDbName = Global.GetDbName(strReaderRecPath); string strLibraryCode = Program.MainForm.GetReaderDbLibraryCode(strReaderDbName); ReaderLine line = null; // XML 记录变换为 SQL 记录 int nRet = ReaderLine.Xml2Line(dom, strReaderRecPath, strLibraryCode, out line, out strError); if (nRet == -1) return -1; _updateReaders.Add(line); if (this._updateReaders.Count >= UPDATE_READERS_BATCHSIZE) { nRet = CommitUpdateReaders( connection, out strError); if (nRet == -1) return -1; } return 0; } int CommitUpdateReaders( SQLiteConnection connection, out string strError) { strError = ""; int nRet = 0; if (this._updateReaders.Count == 0) return 0; Debug.WriteLine("CommitUpdateReaders() _updateReaders.Count=" + _updateReaders.Count); // 插入一批读者记录 nRet = ReaderLine.AppendReaderLines( connection, this._updateReaders, true, out strError); if (nRet == -1) return -1; this._updateReaders.Clear(); return 0; } #endregion #if NO // 获得日志文件中记录的总数 // parameters: // strDate 日志文件的日期,8 字符 // return: // -2 此类型的日志在 dp2library 端尚未启用 // -1 出错 // 0 日志文件不存在,或者记录数为 0 // >0 记录数 long GetOperLogCount(string strDate, LogType logType, out string strError) { strError = ""; string strXml = ""; long lAttachmentTotalLength = 0; byte[] attachment_data = null; long lRecCount = 0; string strStyle = "getcount"; if ((logType & LogType.AccessLog) != 0) strStyle += ",accessLog"; // 获得日志文件尺寸 // return: // -1 error // 0 file not found // 1 succeed // 2 超过范围 long lRet = this.Channel.GetOperLog( null, strDate + ".log", -1, // lIndex, -1, // lHint, strStyle, "", // strFilter out strXml, out lRecCount, 0, // lAttachmentFragmentStart, 0, // nAttachmentFramengLength, out attachment_data, out lAttachmentTotalLength, out strError); if (lRet == 0) { lRecCount = 0; return 0; } if (lRet != 1) return -1; if (lRecCount == -1) { strError = logType.ToString() + " 型的日志在 dp2library 中尚未启用"; return -2; } Debug.Assert(lRecCount >= 0, ""); return lRecCount; } #endif // 执行每日同步任务 // 从上次记忆的断点位置,开始同步 private void button_start_dailyReplication_Click(object sender, EventArgs e) { #if NO string strError = ""; int nRet = 0; nRet = DoDailyReplication(LogType.OperLog, out strError); if (nRet == -1) goto ERROR1; nRet = DoDailyReplication(LogType.AccessLog, out strError); if (nRet == -1) goto ERROR1; MessageBox.Show(this, "处理完成"); return; ERROR1: MessageBox.Show(this, strError); #endif #if NO Task.Factory.StartNew(() => DoDailyReplication(LogType.OperLog), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default) .ContinueWith((antecendent) => { if (antecendent.IsFaulted == true) { this.Invoke((Action)(() => MessageBox.Show(this, ExceptionUtil.GetDebugText(antecendent.Exception)))); return; } Task.Factory.StartNew(() => DoDailyReplication(LogType.AccessLog), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); }) .ContinueWith((antecendent) => { if (antecendent.IsFaulted == true) { this.Invoke((Action)(() => MessageBox.Show(this, ExceptionUtil.GetDebugText(antecendent.Exception)))); return; } this.Invoke((Action)(() => MessageBox.Show(this, "处理完成"))); }); #endif Thread thread = new Thread(new ThreadStart(this.DoDailyReplication)); thread.Start(); } void DoDailyReplication() { string strError = ""; int nRet = 0; nRet = DoDailyReplication(LogType.OperLog, out strError); if (nRet == -1) goto ERROR1; nRet = DoDailyReplication(LogType.AccessLog, out strError); if (nRet == -1) goto ERROR1; this.Invoke((Action)(() => MessageBox.Show(this, "处理完成"))); return; ERROR1: this.Invoke((Action)(() => MessageBox.Show(this, strError))); } void DoDailyReplication( LogType logType) { string strError = ""; try { int nRet = DoDailyReplication(logType, out strError); if (nRet == -1) this.Invoke((Action)(() => MessageBox.Show(this, strError))); } catch (Exception ex) { strError = "每日同步时出现异常: " + ExceptionUtil.GetDebugText(ex); ReportException(strError); } } // 执行每日同步任务 // 从上次记忆的断点位置,开始同步 // return: // -1 出错 // 0 没有必要进行同步。因为指定类型的日志在服务器端尚未启用 // 1 成功 int DoDailyReplication( LogType logType, out string strError) { strError = ""; int nRet = 0; string strEndDate = ""; long lIndex = 0; string strState = ""; // 读入每日同步断点信息 // return: // -1 出错 // 0 正常 // 1 首次创建尚未完成 nRet = LoadDailyBreakPoint( logType, out strEndDate, out lIndex, out strState, out strError); if (nRet == -1) goto ERROR1; if (nRet == 1 || strState != "daily") { strError = "首次创建尚未完成。必须完成后才能进行每日同步"; goto ERROR1; } if (string.IsNullOrEmpty(strEndDate) == true && (logType & LogType.AccessLog) != 0) { strError = logType.ToString() + " 型的日志没有启用"; return 0; } // TODO: 如果 strEndDate 为空,则需要设定为一个较早的时间 // 还可以提醒,说以前并没有作第一次操作 // 特殊情况下,因为一个数据库都是空的,无法做第一次操作?需要验证一下 // 第一次操作完成后,其按钮应该发灰,后面只能做每日创建。另有一个功能可以清除以前的信息,然后第一次的按钮又可以使用了 string strToday = DateTimeUtil.DateTimeToString8(DateTime.Now); string strLastDate = ""; long last_index = 0; try { // return: // -1 出错 // 0 中断 // 1 完成 nRet = DoReplication( strEndDate + ":" + lIndex.ToString() + "-", strToday, logType, // long index, out strLastDate, out last_index, out strError); if (nRet == -1) goto ERROR1; #if NO MessageBox.Show(this, "nRet=" + nRet.ToString()); MessageBox.Show(this, strLastDate); MessageBox.Show(this, last_index.ToString()); #endif // 如果结束的日期小于今天 if (nRet == 1 // 正常完成 // && string.IsNullOrEmpty(strLastDate) == false && last_index != -1 && string.Compare(strLastDate, strToday) < 0) { // 把断点设置为今天的开始 strLastDate = strToday; last_index = 0; } } finally { // 写入每日同步断点信息 if (string.IsNullOrEmpty(strLastDate) == false && last_index != -1) { string strError_1 = ""; nRet = WriteDailyBreakPoint( logType, strLastDate, last_index, out strError_1); if (nRet == -1) { this.Invoke((Action)(() => { MessageBox.Show(this, strError_1); })); } } SetStartButtonStates(); SetDailyReportButtonState(); } return 1; ERROR1: return -1; } /// <summary> /// 处理对话框键 /// </summary> /// <param name="keyData">System.Windows.Forms.Keys 值之一,它表示要处理的键。</param> /// <returns>如果控件处理并使用击键,则为 true;否则为 false,以允许进一步处理</returns> protected override bool ProcessDialogKey( Keys keyData) { // Keys pure_key = (keyData & (~(Keys.Control | Keys.Shift | Keys.Alt))); Keys pure_key = (keyData & Keys.KeyCode); Debug.WriteLine(pure_key.ToString()); if (Control.ModifierKeys == Keys.Control && pure_key == Keys.Enter) { if (Control.ModifierKeys == Keys.Control) { SQLiteQuery(); return true; } } if (keyData == Keys.Escape) { this.DialogResult = DialogResult.Cancel; this.Close(); return true; } // return false; return base.ProcessDialogKey(keyData); } List<int> _resultColumnWidths = new List<int>(); /* 空 SQL 语句容易造成: 发生未捕获的界面线程异常: Type: System.NullReferenceException Message: 未将对象引用设置到对象的实例。 Stack: 在 System.Data.SQLite.SQLiteDataReader.Read() 在 dp2Circulation.ReportForm.SQLiteQuery() 在 dp2Circulation.ReportForm.toolStripButton_query_do_Click(Object sender, EventArgs e) 在 System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e) 在 System.Windows.Forms.ToolStripButton.OnClick(EventArgs e) 在 System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e) 在 System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e) 在 System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea) 在 System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) 在 System.Windows.Forms.Control.WndProc(Message& m) 在 System.Windows.Forms.ToolStrip.WndProc(Message& m) 在 System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) * */ void SQLiteQuery() { string strError = ""; // int nRet = 0; if (string.IsNullOrEmpty(this.textBox_query_command.GetText().Trim()) == true) { strError = "尚未输入 SQL 语句"; goto ERROR1; } EnableControls(false); this.ChannelDoEvents = !this.InvokeRequired; stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在查询数据库 ..."); stop.BeginLoop(); this.listView_query_results.BeginUpdate(); this.timer_qu.Start(); try { // 保留以前的列宽度 for (int i = 0; i < this.listView_query_results.Columns.Count; i++) { if (_resultColumnWidths.Count <= i) _resultColumnWidths.Add(100); _resultColumnWidths[i] = this.listView_query_results.Columns[i].Width; } this.listView_query_results.Clear(); this._connectionString = GetOperlogConnectionString(); // SQLiteUtil.GetConnectionString(Program.MainForm.UserDir, "operlog.bin"); using (SQLiteConnection connection = new SQLiteConnection(this._connectionString)) { connection.Open(); using (SQLiteCommand command = new SQLiteCommand(this.textBox_query_command.GetText(), connection)) { try { SQLiteDataReader dr = command.ExecuteReader(CommandBehavior.SingleResult); try { // 如果记录不存在 if (dr == null || dr.HasRows == false) return; if (dr.FieldCount == 0) { strError = "结果中不包含任何列"; goto ERROR1; } // 设置列标题 for (int i = 0; i < dr.FieldCount; i++) { ColumnHeader header = new ColumnHeader(); header.Text = dr.GetName(i); if (_resultColumnWidths.Count <= i) _resultColumnWidths.Add(100); header.Width = this._resultColumnWidths[i]; // 恢复列宽度 this.listView_query_results.Columns.Add(header); } int nCount = 0; // 如果记录已经存在 while (dr.Read()) { if (this.InvokeRequired == false) Application.DoEvents(); if (stop != null && stop.State != 0) { strError = "用户中断..."; goto ERROR1; } ListViewItem item = new ListViewItem(); for (int i = 0; i < dr.FieldCount; i++) { ListViewUtil.ChangeItemText(item, i, dr.GetValue(i).ToString()); } this.listView_query_results.Items.Add(item); nCount++; if ((nCount % 1000) == 0) stop.SetMessage(nCount.ToString()); } } finally { dr.Close(); } } catch (SQLiteException ex) { strError = "执行SQL语句发生错误: " + ex.Message + "\r\nSQL 语句: " + this.textBox_query_command.GetText(); goto ERROR1; } } } } finally { this.timer_qu.Stop(); this.listView_query_results.EndUpdate(); stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); stop.HideProgress(); EnableControls(true); } return; ERROR1: this.Invoke((Action)(() => { MessageBox.Show(this, strError); })); } private void toolStripButton_query_do_Click(object sender, EventArgs e) { SQLiteQuery(); } #region ErrorInfoForm /// <summary> /// 错误信息窗 /// </summary> public HtmlViewerForm ErrorInfoForm = null; // 获得错误信息窗 internal HtmlViewerForm GetErrorInfoForm() { this.Invoke((Action)(() => { if (this.ErrorInfoForm == null || this.ErrorInfoForm.IsDisposed == true || this.ErrorInfoForm.IsHandleCreated == false) { this.ErrorInfoForm = new HtmlViewerForm(); this.ErrorInfoForm.ShowInTaskbar = false; this.ErrorInfoForm.Text = "错误信息"; this.ErrorInfoForm.Show(this); this.ErrorInfoForm.WriteHtml("<pre>"); // 准备文本输出 } })); return this.ErrorInfoForm; } // 清除错误信息窗口中残余的内容 internal void ClearErrorInfoForm() { if (this.ErrorInfoForm != null) { try { this.ErrorInfoForm.HtmlString = "<pre>"; } catch { } } } #endregion private void checkBox_start_enableFirst_CheckedChanged(object sender, EventArgs e) { if (this.checkBox_start_enableFirst.Checked == true) { string strError = ""; string strEndDate = ""; long lIndex = 0; string strState = ""; // 读入断点信息 // return: // -1 出错 // 0 正常 // 1 首次创建尚未完成 int nRet = LoadDailyBreakPoint( out strEndDate, out lIndex, out strState, out strError); if (nRet == -1) { this.Invoke((Action)(() => { MessageBox.Show(this, strError); })); return; } if (strState == "first" || strState == "daily") { DialogResult temp_result = MessageBox.Show(this, "重新从头创建本地存储,需要清除当前的断点信息。\r\n\r\n确实要这样做?", "ReportForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (temp_result == System.Windows.Forms.DialogResult.No) return; ClearBreakPoint(); } this.button_start_createLocalStorage.Enabled = true; } } // 获得显示用的馆代码形态 public static string GetDisplayLibraryCode(string strLibraryCode) { if (string.IsNullOrEmpty(strLibraryCode) == true) return "[全局]"; return strLibraryCode; } // 获得内部用的官代码形态 public static string GetOriginLibraryCode(string strDisplayText) { if (strDisplayText == "[全局]") return ""; return strDisplayText; } // 只创建选定分馆的报表 void menu_createSelectedLibraryReport_Click(object sender, EventArgs e) { string strError = ""; int nRet = 0; #if SN #if REPORT_SN nRet = Program.MainForm.VerifySerialCode("report", false, out strError); if (nRet == -1) { MessageBox.Show("创建报表功能尚未被许可"); return; } #endif #endif string strTaskFileName = Path.Combine(GetBaseDirectory(), "dailyreport_task.xml"); XmlDocument task_dom = new XmlDocument(); if (File.Exists(strTaskFileName) == true) { DialogResult result = MessageBox.Show(this, "发现上次创建报表的任务被中断过,尚未完成。\r\n\r\n是否从断点位置继续处理?\r\n\r\n(是)继续处理; (否)从头开始处理; (取消)放弃全部处理", "ReportForm", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (result == System.Windows.Forms.DialogResult.Cancel) return; if (result == System.Windows.Forms.DialogResult.Yes) { try { task_dom.Load(strTaskFileName); goto DO_TASK; } catch (Exception ex) { strError = "装载文件 '" + strTaskFileName + "' 到 XMLDOM 时出错: " + ex.Message; goto ERROR1; } } } task_dom.LoadXml("<root />"); File.Delete(strTaskFileName); strTaskFileName = ""; if (this.listView_libraryConfig.SelectedItems.Count == 0) { strError = "尚未选定要创建报表的分馆事项"; goto ERROR1; } ListViewItem first_item = this.listView_libraryConfig.SelectedItems[0]; string strFirstLibraryCode = ListViewUtil.GetItemText(first_item, 0); strFirstLibraryCode = GetOriginLibraryCode(strFirstLibraryCode); XmlNode nodeFirstLibrary = this._cfg.GetLibraryNode(strFirstLibraryCode); if (nodeFirstLibrary == null) { strError = "在配置文件中没有找到馆代码为 '" + strFirstLibraryCode + "' 的 <library> 元素"; goto ERROR1; } // 这个日期是上次处理完成的那一天的后一天,也就是说下次处理,从这天开始即可 string strLastDate = Program.MainForm.AppInfo.GetString(GetReportSection(), "daily_report_end_date", "20130101"); // TODO: 特殊允许当天的也参加统计 string strEndDate = DateTimeUtil.DateTimeToString8(DateTime.Now); string strRealEndDate = ""; #if NO List<string> report_names = new List<string>(); XmlNodeList nodes = nodeLibrary.SelectNodes("reports/report"); foreach (XmlNode node in nodes) { string strName = DomUtil.GetAttr(node, "name"); report_names.Add(strName); } #endif string strReportNameList = Program.MainForm.AppInfo.GetString(GetReportSection(), "createwhat_reportnames", ""); // 询问创建报表的时间范围 // 询问那些频率的日期需要创建 // 询问那些报表需要创建 CreateWhatsReportDialog dlg = new CreateWhatsReportDialog(); MainForm.SetControlFont(dlg, this.Font, false); dlg.DateRange = Program.MainForm.AppInfo.GetString(GetReportSection(), "createwhat_daterange", ""); if (string.IsNullOrEmpty(dlg.DateRange) == true) dlg.DateRange = strLastDate + "-" + strEndDate; // 从上次最后处理时间,到今天 dlg.Freguency = Program.MainForm.AppInfo.GetString(GetReportSection(), "createwhat_frequency", "year,month,day"); // dlg.ReportsNames = report_names; dlg.LoadReportList(nodeFirstLibrary); if (string.IsNullOrEmpty(strReportNameList) == false) dlg.SelectedReportsNames = StringUtil.SplitList(strReportNameList, "|||"); Program.MainForm.AppInfo.LinkFormState(dlg, "CreateWhatsReportDialog_state"); dlg.UiState = Program.MainForm.AppInfo.GetString(GetReportSection(), "CreateWhatsReportDialog_ui_state", ""); dlg.ShowDialog(this); Program.MainForm.AppInfo.SetString(GetReportSection(), "CreateWhatsReportDialog_ui_state", dlg.UiState); Program.MainForm.AppInfo.UnlinkFormState(dlg); Program.MainForm.AppInfo.SetString(GetReportSection(), "createwhat_reportnames", StringUtil.MakePathList(dlg.SelectedReportsNames, "|||")); Program.MainForm.AppInfo.SetString(GetReportSection(), "createwhat_frequency", dlg.Freguency); Program.MainForm.AppInfo.SetString(GetReportSection(), "createwhat_daterange", dlg.DateRange); if (dlg.DialogResult == System.Windows.Forms.DialogResult.Cancel) return; List<string> freq_types = StringUtil.SplitList(dlg.Freguency); if (string.IsNullOrEmpty(dlg.Freguency) == true) { freq_types.Add("year"); freq_types.Add("month"); freq_types.Add("day"); } #if NO List<BiblioDbFromInfo> class_styles = null; // 获得所有分类号检索途径 style nRet = GetClassFromStylesFromFile(out class_styles, out strError); if (nRet == -1) goto ERROR1; #endif this.EnableControls(false); stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在规划任务 ..."); stop.BeginLoop(); try { #if NO // 创建必要的索引 this._connectionString = GetOperlogConnectionString(); stop.SetMessage("正在检查和创建 SQL 索引 ..."); foreach (string type in OperLogTable.DbTypes) { nRet = OperLogTable.CreateAdditionalIndex( type, this._connectionString, out strError); if (nRet == -1) goto ERROR1; } // 删除所有先前复制出来的 class 表 nRet = DeleteAllDistinctClassTable(out strError); if (nRet == -1) goto ERROR1; #endif // CloseIndexXmlDocument(); try { // 获得本窗口选用了的馆代码 List<string> librarycodes = this.GetLibraryCodes(false); foreach (string strLibraryCode in librarycodes) { if (this.InvokeRequired == false) Application.DoEvents(); XmlElement library_element = task_dom.CreateElement("library"); task_dom.DocumentElement.AppendChild(library_element); library_element.SetAttribute("code", strLibraryCode); foreach (string strTimeType in freq_types) { List<string> report_names = new List<string>(); if (string.IsNullOrEmpty(dlg.Freguency) == true) { // 每个报表都有独特的频率,选出符合频率的报表 foreach (string strReportName in dlg.SelectedReportsNames) { if (dlg.GetReportFreq(strReportName).IndexOf(strTimeType) == -1) continue; report_names.Add(strReportName); } if (report_names.Count == 0) continue; } else { report_names = dlg.SelectedReportsNames; } List<OneTime> times = null; // parameters: // strType 时间单位类型。 year month week day 之一 nRet = GetTimePoints( strTimeType, dlg.DateRange, // 可以使用 2013 这样的表示一年的范围的 false, out strRealEndDate, out times, out strError); if (nRet == -1) goto ERROR1; foreach (OneTime time in times) { // stop.SetMessage("正在创建 " + GetDisplayLibraryCode(strLibraryCode) + " " + time.Time + " 的报表"); if (this.InvokeRequired == false) Application.DoEvents(); if (stop != null && stop.State != 0) { strError = "中断"; goto ERROR1; } bool bTailTime = false; // 是否为本轮最后一个(非探测)时间 if (times.IndexOf(time) == times.Count - 1 && strTimeType != "free") { if (time.Detect == false) bTailTime = true; } Debug.Assert(report_names.Count > 0, ""); XmlElement item_element = task_dom.CreateElement("item"); library_element.AppendChild(item_element); item_element.SetAttribute("timeType", strTimeType); item_element.SetAttribute("time", time.ToString()); item_element.SetAttribute("isTail", bTailTime ? "true" : "false"); item_element.SetAttribute("reportNames", StringUtil.MakePathList(report_names, "|||")); #if NO nRet = CreateOneTimeReports( strTimeType, time, bTailTime, // times, strLibraryCode, report_names, class_styles, out strError); if (nRet == -1) goto ERROR1; #endif } } } } finally { // CloseIndexXmlDocument(); } #if NO // 删除所有先前复制出来的 class 表 nRet = DeleteAllDistinctClassTable(out strError); if (nRet == -1) goto ERROR1; #endif } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); stop.HideProgress(); this.EnableControls(true); } // 由于没有修改报表最后时间,所以“每日报表”按钮状态和文字没有变化 strTaskFileName = Path.Combine(GetBaseDirectory(), "dailyreport_task.xml"); task_dom.Save(strTaskFileName); // 预先保存一次 DO_TASK: #if NO nRet = DoDailyReportTask( ref task_dom, out strError); if (nRet == -1) goto ERROR1; else File.Delete(strTaskFileName); // 任务完成,删除任务文件 #endif Task.Factory.StartNew(() => DoDailyReportTask(strTaskFileName, task_dom), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); return; ERROR1: if (task_dom != null && string.IsNullOrEmpty(strTaskFileName) == false) task_dom.Save(strTaskFileName); MessageBox.Show(this, strError); } delegate void Delegate_SetUploadButtonText(string strText, string strEnabled); internal void SetUploadButtonText(string strText, string strEnabled) { if (this.InvokeRequired == true) { Delegate_SetUploadButtonText d = new Delegate_SetUploadButtonText(SetUploadButtonText); this.BeginInvoke(d, new object[] { strText, strEnabled }); return; } this.button_start_uploadReport.Text = strText; if (strEnabled == "true") this.button_start_uploadReport.Enabled = true; if (strEnabled == "false") this.button_start_uploadReport.Enabled = false; } // 设置 “每日报表” 按钮的状态和文字 // 当每日同步结束后,或者修改了最后统计日期后,需要更新这个按钮的状态 void SetDailyReportButtonState() { string strError = ""; string strRange = ""; // return: // -1 出错 // 0 报表已经是最新状态。strError 中有提示信息 // 1 获得了可以用于处理的范围字符串。strError 中没有提示信息 int nRet = GetDailyReportRangeString(out strRange, out strError); if (nRet == -1 || nRet == 0) { this.Invoke((Action)(() => this.button_start_dailyReport.Text = "每日报表 " + strError )); } else { this.Invoke((Action)(() => this.button_start_dailyReport.Text = "每日报表 " + strRange )); } if (string.IsNullOrEmpty(strRange) == true) { this.Invoke((Action)(() => this.button_start_dailyReport.Enabled = false )); } else { this.Invoke((Action)(() => this.button_start_dailyReport.Enabled = true )); } } // 已经创建唯一事项表的原始 classtable 的名字列表 Hashtable _classtable_nametable = new Hashtable(); int PrepareDistinctClassTable( string strTableName, out string strError) { strError = ""; if (_classtable_nametable.ContainsKey(strTableName) == true) return 0; int nRet = ClassLine.CreateDistinctClassTable(this._connectionString, strTableName, strTableName + "_d", out strError); if (nRet == -1) return -1; _classtable_nametable[strTableName] = true; return 0; } // 删除所有先前复制出来的 class 表 int DeleteAllDistinctClassTable(out string strError) { strError = ""; foreach (string strTableName in this._classtable_nametable.Keys) { int nRet = ClassLine.DeleteClassTable(this._connectionString, strTableName + "_d", out strError); if (nRet == -1) return -1; } this._classtable_nametable.Clear(); return 0; } // 要创建的文件类型 [Flags] enum FileType { RML = 0x01, HTML = 0x02, Excel = 0x04, } FileType _fileType = FileType.RML; // | FileType.HTML; // | FileType.Excel; // 每日增量创建报表 private void button_start_dailyReport_Click(object sender, EventArgs e) { // 需要记忆一个最原始的开始时间。如果没有,就从首次创建本地存储的开始有日志文件的时间 // 从这个时间开始,检查每年、每月、每周、每日的报表是否满足创建的时间条件 // 每日的报表,倒着检查时间即可。到了一个已经创建过的日子,就停止检查 string strError = ""; int nRet = 0; #if SN #if REPORT_SN nRet = Program.MainForm.VerifySerialCode("report", false, out strError); if (nRet == -1) { MessageBox.Show("创建报表功能尚未被许可"); return; } #endif #endif bool bFirst = false; // 是否为第一次做 string strTaskFileName = Path.Combine(GetBaseDirectory(), "dailyreport_task.xml"); XmlDocument task_dom = new XmlDocument(); if (File.Exists(strTaskFileName) == true) { DialogResult result = MessageBox.Show(this, "发现上次创建报表的任务被中断过,尚未完成。\r\n\r\n是否从断点位置继续处理?\r\n\r\n(是)继续处理; (否)从头开始处理; (取消)放弃全部处理", "ReportForm", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (result == System.Windows.Forms.DialogResult.Cancel) return; if (result == System.Windows.Forms.DialogResult.Yes) { try { task_dom.Load(strTaskFileName); goto DO_TASK; } catch (Exception ex) { strError = "装载文件 '" + strTaskFileName + "' 到 XMLDOM 时出错: " + ex.Message; goto ERROR1; } } } task_dom.LoadXml("<root />"); File.Delete(strTaskFileName); strTaskFileName = ""; #if NO // 获得上次处理的末尾日期 // 这个日期是上次处理完成的那一天的后一天,也就是说下次处理,从这天开始即可 string strLastDay = Program.MainForm.AppInfo.GetString(GetReportSection(), "daily_report_end_date", ""); if (string.IsNullOrEmpty(strLastDay) == true) { strError = "当前尚未配置上次统计最末日期"; goto ERROR1; } // 当天日期 string strEndDay = DateTimeUtil.DateTimeToString8(DateTime.Now); #endif string strRange = ""; // 获得即将执行的每日报表的时间范围 // return: // -1 出错 // 0 报表已经是最新状态。strError 中有提示信息 // 1 获得了可以用于处理的范围字符串。strError 中没有提示信息 nRet = GetDailyReportRangeString(out strRange, out strError); if (nRet == -1) goto ERROR1; if (nRet == 0) goto ERROR1; // List<BiblioDbFromInfo> class_styles = null; // 看看是不是首次执行 { string strFileName = Path.Combine(GetBaseDirectory(), "report_breakpoint.xml"); XmlDocument dom = new XmlDocument(); try { dom.Load(strFileName); } catch (FileNotFoundException) { dom.LoadXml("<root />"); } catch (Exception ex) { strError = "装载文件 '" + strFileName + "' 时出错: " + ex.Message; goto ERROR1; } string strFirstDate = DomUtil.GetAttr(dom.DocumentElement, "first_operlog_date"); string strLastDay = Program.MainForm.AppInfo.GetString(GetReportSection(), "daily_report_end_date", ""); if (strFirstDate == strLastDay) bFirst = true; else bFirst = false; #if NO // 获得所有分类号检索途径 style nRet = GetClassFromStyles( dom.DocumentElement, out class_styles, out strError); if (nRet == -1) goto ERROR1; #endif } #if NO // 装载上次部分完成的名字表 nRet = LoadDoneTable(out strError); if (nRet == -1) goto ERROR1; if (this._doneTable.Count > 0) { MessageBox.Show(this, "上次任务已经完成 " + this._doneTable.Count.ToString() + " 个事项,本次将从断点继续进行处理"); } #endif string strRealEndDate = ""; // bool bFoundReports = false; // 获得本窗口全部馆代码 List<string> librarycodes = this.GetLibraryCodes(); if (librarycodes.Count == 0) { strError = "尚未配置任何分馆的报表。请先到 “报表配置” 属性页配置好报表"; goto ERROR1; } this.EnableControls(false); stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在规划任务 ..."); stop.BeginLoop(); try { #if NO // 创建必要的索引 this._connectionString = GetOperlogConnectionString(); stop.SetMessage("正在检查和创建 SQL 索引 ..."); foreach (string type in OperLogTable.DbTypes) { if (this.InvokeRequired == false) Application.DoEvents(); nRet = OperLogTable.CreateAdditionalIndex( type, this._connectionString, out strError); if (nRet == -1) goto ERROR1; } // 删除所有先前复制出来的 class 表 nRet = DeleteAllDistinctClassTable(out strError); if (nRet == -1) goto ERROR1; #endif List<string> types = new List<string>(); types.Add("year"); types.Add("month"); types.Add("day"); foreach (string strLibraryCode in librarycodes) { if (this.InvokeRequired == false) Application.DoEvents(); XmlElement library_element = task_dom.CreateElement("library"); task_dom.DocumentElement.AppendChild(library_element); library_element.SetAttribute("code", strLibraryCode); try { foreach (string strTimeType in types) { if (this.InvokeRequired == false) Application.DoEvents(); List<OneTime> times = null; // parameters: // strType 时间单位类型。 year month week day 之一 nRet = GetTimePoints( strTimeType, strRange, // strLastDay + "-" + strEndDay, !bFirst, out strRealEndDate, out times, out strError); if (nRet == -1) goto ERROR1; foreach (OneTime time in times) { // stop.SetMessage("正在创建 " + GetDisplayLibraryCode(strLibraryCode) + " " + time.Time + " 的报表"); if (this.InvokeRequired == false) Application.DoEvents(); if (stop != null && stop.State != 0) { strError = "中断"; goto ERROR1; } bool bTailTime = false; // 是否为本轮最后一个(非探测)时间 if (times.IndexOf(time) == times.Count - 1) { if (time.Detect == false) bTailTime = true; } XmlElement item_element = task_dom.CreateElement("item"); library_element.AppendChild(item_element); item_element.SetAttribute("timeType", strTimeType); item_element.SetAttribute("time", time.ToString()); // item_element.SetAttribute("times", OneTime.TimesToString(times)); item_element.SetAttribute("isTail", bTailTime ? "true" : "false"); #if NO // return: // -1 出错 // 0 没有任何匹配的报表 // 1 成功处理 nRet = CreateOneTimeReports( strTimeType, time, times, strLibraryCode, null, class_styles, out strError); if (nRet == -1) goto ERROR1; if (nRet == 1) bFoundReports = true; #endif } } } finally { // CloseIndexXmlDocument(); } } #if NO // 删除所有先前复制出来的 class 表 nRet = DeleteAllDistinctClassTable(out strError); if (nRet == -1) goto ERROR1; #endif } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); stop.HideProgress(); this.EnableControls(true); } #if NO // 删除遗留信息文件 nRet = SaveDoneTable( true, out strError); if (nRet == -1) goto ERROR1; #endif task_dom.DocumentElement.SetAttribute("realEndDate", strRealEndDate); #if NO if (string.IsNullOrEmpty(strRealEndDate) == false) { // 这个日期是上次处理完成的那一天的后一天,也就是说下次处理,从这天开始即可 Program.MainForm.AppInfo.SetString(GetReportSection(), "daily_report_end_date", GetNextDate(strRealEndDate)); SetDailyReportButtonState(); } SetUploadButtonState(); if (bFoundReports == false) MessageBox.Show(this, "当前没有任何报表配置可供创建报表。请先去“报表配置”属性页配置好各个分馆的报表"); #endif strTaskFileName = Path.Combine(GetBaseDirectory(), "dailyreport_task.xml"); task_dom.Save(strTaskFileName); // 预先保存一次 DO_TASK: #if NO nRet = DoDailyReportTask( ref task_dom, out strError); if (nRet == -1) goto ERROR1; else File.Delete(strTaskFileName); // 任务完成,删除任务文件 #endif Task.Factory.StartNew(() => DoDailyReportTask(strTaskFileName, task_dom), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); return; ERROR1: if (task_dom != null && string.IsNullOrEmpty(strTaskFileName) == false) task_dom.Save(strTaskFileName); MessageBox.Show(this, strError); } void ClearCache() { this._writerCache.Clear(); this._libraryLocationCache.Clear(); } void DoDailyReportTask( string strTaskFileName, XmlDocument task_dom) { string strError = ""; try { int nRet = DoDailyReportTask(ref task_dom, out strError); if (nRet == -1) { if (task_dom != null && string.IsNullOrEmpty(strTaskFileName) == false) task_dom.Save(strTaskFileName); this.ShowMessage(strError, "red", true); this.Invoke((Action)(() => MessageBox.Show(this, strError))); } else File.Delete(strTaskFileName); // 任务完成,删除任务文件 } catch (Exception ex) { strError = "创建报表时出现异常: " + ExceptionUtil.GetDebugText(ex); ReportException(strError); } } // 线程安全版本 // 每日增量创建报表 // return: // -1 出错,或者中断 // 0 没有任何配置的报表 // 1 成功 int DoDailyReportTask( ref XmlDocument task_dom, out string strError) { strError = ""; int nRet = 0; #if SN #if REPORT_SN nRet = Program.MainForm.VerifySerialCode("report", false, out strError); if (nRet == -1) { strError = "创建报表功能尚未被许可"; goto ERROR1; } #endif #endif int nDoneCount = 0; ClearCache(); if (DomUtil.GetIntegerParam(task_dom.DocumentElement, "doneCount", 0, out nDoneCount, out strError) == -1) goto ERROR1; List<BiblioDbFromInfo> class_styles = null; // 从计划文件获得所有分类号检索途径 style nRet = GetClassFromStylesFromFile( out class_styles, out strError); if (nRet == -1) goto ERROR1; // string strRealEndDate = ""; bool bFoundReports = false; this.EnableControls(false); stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在创建报表 ..."); stop.BeginLoop(); try { // 创建必要的索引 this._connectionString = GetOperlogConnectionString(); stop.SetMessage("正在检查和创建 SQL 索引 ..."); foreach (string type in OperLogTable.DbTypes) { // Application.DoEvents(); nRet = OperLogTable.CreateAdditionalIndex( type, this._connectionString, out strError); if (nRet == -1) goto ERROR1; } // 删除所有先前复制出来的 class 表 nRet = DeleteAllDistinctClassTable(out strError); if (nRet == -1) goto ERROR1; XmlNodeList all_item_nodes = task_dom.DocumentElement.SelectNodes("library/item"); stop.SetProgressRange(0, all_item_nodes.Count + nDoneCount); _estimate.SetRange(0, all_item_nodes.Count + nDoneCount); _estimate.StartEstimate(); XmlNodeList library_nodes = task_dom.DocumentElement.SelectNodes("library"); int i = nDoneCount; stop.SetProgressValue(i); foreach (XmlElement library_element in library_nodes) { if (this.InvokeRequired == false) Application.DoEvents(); string strLibraryCode = library_element.GetAttribute("code"); XmlNodeList item_nodes = library_element.SelectNodes("item"); foreach (XmlElement item_element in item_nodes) { string strTimeType = item_element.GetAttribute("timeType"); OneTime time = OneTime.FromString(item_element.GetAttribute("time")); // List<OneTime> times = OneTime.TimesFromString(item_element.GetAttribute("times")); bool bTailTime = DomUtil.IsBooleanTrue(item_element.GetAttribute("isTail")); List<string> report_names = StringUtil.SplitList(item_element.GetAttribute("reportNames"), "|||"); if (report_names.Count == 0) report_names = null; stop.SetMessage("正在创建 " + GetDisplayLibraryCode(strLibraryCode) + " " + time.Time + " 的报表。" + GetProgressTimeString(i)); if (this.InvokeRequired == false) Application.DoEvents(); if (stop != null && stop.State != 0) { strError = "中断"; goto ERROR1; } // return: // -1 出错 // 0 没有任何匹配的报表 // 1 成功处理 nRet = CreateOneTimeReports( strTimeType, time, bTailTime, // times, strLibraryCode, report_names, class_styles, out strError); if (nRet == -1) goto ERROR1; if (nRet == 1) bFoundReports = true; item_element.ParentNode.RemoveChild(item_element); // 做过的报表事项, 从 task_dom 中删除 nDoneCount++; i++; stop.SetProgressValue(i); } // fileType 没有 html 的时候,不要创建 index.html 文件 if ((this._fileType & FileType.HTML) != 0) { string strOutputDir = GetReportOutputDir(strLibraryCode); string strIndexXmlFileName = Path.Combine(strOutputDir, "index.xml"); string strIndexHtmlFileName = Path.Combine(strOutputDir, "index.html"); if (stop != null) stop.SetMessage("正在创建 " + strIndexHtmlFileName); // 根据 index.xml 文件创建 index.html 文件 nRet = CreateIndexHtmlFile(strIndexXmlFileName, strIndexHtmlFileName, out strError); if (nRet == -1) goto ERROR1; } } // 删除所有先前复制出来的 class 表 nRet = DeleteAllDistinctClassTable(out strError); if (nRet == -1) goto ERROR1; } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); stop.HideProgress(); this.EnableControls(true); task_dom.DocumentElement.SetAttribute("doneCount", nDoneCount.ToString()); } ShrinkIndexCache(true); #if NO // 删除遗留信息文件 nRet = SaveDoneTable( true, out strError); if (nRet == -1) goto ERROR1; #endif string strRealEndDate = task_dom.DocumentElement.GetAttribute("realEndDate"); if (string.IsNullOrEmpty(strRealEndDate) == false) { // 这个日期是上次处理完成的那一天的后一天,也就是说下次处理,从这天开始即可 Program.MainForm.AppInfo.SetString(GetReportSection(), "daily_report_end_date", GetNextDate(strRealEndDate)); SetDailyReportButtonState(); } // SetUploadButtonState(); BeginUpdateUploadButtonText(); #if NO if (bFoundReports == false) MessageBox.Show(this, "当前没有任何报表配置可供创建报表。请先去“报表配置”属性页配置好各个分馆的报表"); #endif if (bFoundReports == false) { strError = "当前没有任何报表配置可供创建报表。请先去“报表配置”属性页配置好各个分馆的报表"; return 0; } ClearCache(); this.Invoke((Action)(() => Program.MainForm.StatusBarMessage = "耗费时间 " + ProgressEstimate.Format(_estimate.delta_passed) )); return 1; ERROR1: #if NO { string strError1 = ""; // 中间出错,或者中断,保存遗留信息文件 nRet = SaveDoneTable( false, out strError1); if (nRet == -1) MessageBox.Show(this, strError1); } MessageBox.Show(this, strError); #endif ClearCache(); ShrinkIndexCache(true); return -1; } // 获得和当前服务器、用户相关的报表窗配置 section 名字字符串 string GetReportSection() { string strServerUrl = ReportForm.GetValidPathString(Program.MainForm.LibraryServerUrl.Replace("/", "_")); return "r_" + strServerUrl + "_" + ReportForm.GetValidPathString(Program.MainForm.GetCurrentUserName()); } // 获得即将执行的每日报表的时间范围 // return: // -1 出错 // 0 报表已经是最新状态。strError 中有提示信息 // 1 获得了可以用于处理的范围字符串。strError 中没有提示信息 int GetDailyReportRangeString(out string strRange, out string strError) { strRange = ""; strError = ""; // 获得上次处理的末尾日期 // 这个日期是上次处理完成的那一天的后一天,也就是说下次处理,从这天开始即可 string strLastDay = Program.MainForm.AppInfo.GetString(GetReportSection(), "daily_report_end_date", ""); if (string.IsNullOrEmpty(strLastDay) == true) { strError = "尚未配置报表创建起点日期"; return -1; } DateTime start; try { start = DateTimeUtil.Long8ToDateTime(strLastDay); } catch { strError = "开始日期 '" + strLastDay + "' 不合法。应该是 8 字符的日期格式"; return -1; } string strDailyEndDate = ""; { long lIndex = 0; string strState = ""; // 读入断点信息 // return: // -1 出错 // 0 正常 // 1 首次创建尚未完成 int nRet = LoadDailyBreakPoint( out strDailyEndDate, out lIndex, out strState, out strError); if (nRet == -1) { strError = "获得日志同步最后日期时出错: " + strError; return -1; } if (nRet == 1) { strError = "首次创建本地存储尚未完成,无法创建报表"; return -1; } } DateTime daily_end; try { daily_end = DateTimeUtil.Long8ToDateTime(strDailyEndDate); } catch { strError = "日志同步最后日期 '" + strDailyEndDate + "' 不合法。应该是 8 字符的日期格式"; return -1; } // 两个日期都不允许超过今天 if (start >= daily_end) { // strError = "上次统计最末日期 '"+strLastDay+"' 不应晚于 日志同步最后日期 " + strDailyEndDate + " 的前一天"; // return -1; strError = "报表已经是最新"; if (start > daily_end) strError += " (警告!" + strLastDay + "有误)"; return 0; } DateTime end = daily_end - new TimeSpan(1, 0, 0, 0, 0); string strEndDate = DateTimeUtil.DateTimeToString8(end); if (strLastDay == strEndDate) strRange = strLastDay; // 缩略表示 else strRange = strLastDay + "-" + strEndDate; return 1; } // 获得一个日期的下一天 // parameters: // strDate 8字符的时间格式 static string GetNextDate(string strDate) { DateTime start; try { start = DateTimeUtil.Long8ToDateTime(strDate); } catch { return strDate; // 返回原样的字符串 } return DateTimeUtil.DateTimeToString8(start + new TimeSpan(1, 0, 0, 0, 0)); } // 一个处理时间 class OneTime { public string Time = ""; public bool Detect = false; // 是否要探测这个时间已经做过? true 表示要探测。false 表示无论如何都要做 public OneTime() { } public OneTime(string strTime) { this.Time = strTime; } public OneTime(string strTime, bool bDetect) { this.Time = strTime; this.Detect = bDetect; } public override string ToString() { return this.Time + "|" + (this.Detect == true ? "true" : "false"); } public static OneTime FromString(string strText) { string strTime = ""; string strDetect = ""; StringUtil.ParseTwoPart(strText, "|", out strTime, out strDetect); OneTime result = new OneTime(); result.Time = strTime; result.Detect = DomUtil.IsBooleanTrue(strDetect); return result; } public static string TimesToString(List<OneTime> times) { if (times == null) return ""; StringBuilder text = new StringBuilder(); foreach (OneTime time in times) { if (text.Length > 0) text.Append(","); text.Append(time.ToString()); } return text.ToString(); } public static List<OneTime> TimesFromString(string strText) { List<OneTime> results = new List<OneTime>(); if (string.IsNullOrEmpty(strText) == true) return results; string[] segments = strText.Split(new char[] { ',' }); foreach (string strTime in segments) { results.Add(OneTime.FromString(strTime)); } return results; } } // 获得上个月的 4 字符时间 static string GetPrevMonthString(DateTime current) { if (current.Month == 1) return (current.Year - 1).ToString().PadLeft(4, '0') + "12"; return current.Year.ToString().PadLeft(4, '0') + (current.Month - 1).ToString().PadLeft(2, '0'); } // parameters: // strType 时间单位类型。 year month week day 之一 // strDateRange 日期范围。其中结束日期不允许超过今天。因为今天的日志可能没有同步完 // bDetect 是否要增加一个探测时间值? 根据开始的日期,如果属于每月一号则负责探测上一个月; 如果属于 1 月 1 号则负责探测上一年 // strRealEndDate 返回实际处理完的最后一天 int GetTimePoints( string strType, string strDateRange, bool bDetect, out string strRealEndDate, out List<OneTime> values, out string strError) { strError = ""; values = new List<OneTime>(); strRealEndDate = ""; string strStartDate = ""; string strEndDate = ""; try { // 将日期字符串解析为起止范围日期 // throw: // Exception DateTimeUtil.ParseDateRange(strDateRange, out strStartDate, out strEndDate); // 2014/3/19 if (string.IsNullOrEmpty(strEndDate) == true) strEndDate = strStartDate; } catch (Exception) { strError = "日期范围字符串 '" + strDateRange + "' 格式不正确"; return -1; } DateTime start; try { start = DateTimeUtil.Long8ToDateTime(strStartDate); } catch { strError = "统计日期范围 '" + strDateRange + "' 中的开始日期 '" + strStartDate + "' 不合法。应该是 8 字符的日期格式"; return -1; } DateTime end; try { end = DateTimeUtil.Long8ToDateTime(strEndDate); } catch { strError = "统计日期范围 '" + strDateRange + "' 中的结束日期 '" + strEndDate + "' 不合法。应该是 8 字符的日期格式"; return -1; } string strDailyEndDate = ""; { long lIndex = 0; string strState = ""; // 读入断点信息 // return: // -1 出错 // 0 正常 // 1 首次创建尚未完成 int nRet = LoadDailyBreakPoint( out strDailyEndDate, out lIndex, out strState, out strError); if (nRet == -1) { strError = "获得日志同步最后日期时出错: " + strError; return -1; } if (nRet == 1) { strError = "首次创建本地存储尚未完成,无法创建报表"; return -1; } } #if NO DateTime now = DateTime.Now; now = now.Date; // 只取日期部分 #endif DateTime daily_end; try { daily_end = DateTimeUtil.Long8ToDateTime(strDailyEndDate); } catch { strError = "日志同步最后日期 '" + strDailyEndDate + "' 不合法。应该是 8 字符的日期格式"; return -1; } // 两个日期都不允许超过今天 if (start >= daily_end) { strError = "统计时间范围的起点不应晚于 日志同步最后日期 " + strDailyEndDate + " 的前一天"; return -1; } if (end >= daily_end) end = daily_end - new TimeSpan(1, 0, 0, 0, 0); strRealEndDate = DateTimeUtil.DateTimeToString8(end); DateTime end_plus_one = end + new TimeSpan(1, 0, 0, 0, 0); if (strType == "free") { { OneTime time = new OneTime(DateTimeUtil.DateTimeToString8(start) + "-" + DateTimeUtil.DateTimeToString8(end)); values.Add(time); } } else if (strType == "year") { int nFirstYear = start.Year; if (bDetect == true && start.Month == 1 && start.Day == 1) { // 每年 1 月 1 号,负责探测上一年 OneTime time = new OneTime((start.Year - 1).ToString().PadLeft(4, '0'), true); values.Add(time); } int nEndYear = end_plus_one.Year; for (int nYear = nFirstYear; nYear < nEndYear; nYear++) { OneTime time = new OneTime(nYear.ToString().PadLeft(4, '0')); values.Add(time); } } else if (strType == "month") { if (bDetect == true && start.Month == 1) { // 每月 1 号,负责探测上个月 OneTime time = new OneTime(GetPrevMonthString(start), true); values.Add(time); } DateTime current = new DateTime(start.Year, start.Month, 1); DateTime end_month = new DateTime(end_plus_one.Year, end_plus_one.Month, 1); while (current < end_month) { values.Add(new OneTime(current.Year.ToString().PadLeft(4, '0') + current.Month.ToString().PadLeft(2, '0'))); // 下一个月 if (current.Month >= 12) current = new DateTime(current.Year + 1, 1, 1); else current = new DateTime(current.Year, current.Month + 1, 1); } } else if (strType == "day") { DateTime current = new DateTime(start.Year, start.Month, start.Day); while (current <= end) { values.Add(new OneTime(current.Year.ToString().PadLeft(4, '0') + current.Month.ToString().PadLeft(2, '0') + current.Day.ToString().PadLeft(2, '0'))); // 下一天 current += new TimeSpan(1, 0, 0, 0); } } else if (strType == "week") { strError = "暂不支持 week"; return -1; } return 0; } // 特定分馆的报表输出目录 string GetReportOutputDir(string strLibraryCode) { // return Path.Combine(Program.MainForm.UserDir, "reports\\" + GetValidPathString(GetDisplayLibraryCode(strLibraryCode))); // 2015/6/20 将创建好的报表文件存储在和每个 dp2library 服务器和用户名相关的目录中 return Path.Combine(GetBaseDirectory(), "reports\\" + GetValidPathString(GetDisplayLibraryCode(strLibraryCode))); } // parameters: // nodeLibrary 配置文件中的 library 元素节点。如果为 null,表示取全局缺省的模板 int LoadHtmlTemplate(XmlNode nodeLibrary, out string strTemplate, out string strError) { strTemplate = ""; strError = ""; string strCssTemplateDir = Path.Combine(Program.MainForm.UserDir, "report_def"); // Path.Combine(Program.MainForm.UserDir, "report_def"); string strHtmlTemplate = ""; if (nodeLibrary != null) strHtmlTemplate = DomUtil.GetAttr(nodeLibrary, "htmlTemplate"); if (string.IsNullOrEmpty(strHtmlTemplate) == true) strHtmlTemplate = "default"; string strFileName = Path.Combine(strCssTemplateDir, GetValidPathString(strHtmlTemplate) + ".css"); if (File.Exists(strFileName) == false) { strError = "CSS 模板文件 '" + strFileName + "' 不存在"; return -1; } Encoding encoding; // return: // -1 出错 strError中有返回值 // 0 文件不存在 strError中有返回值 // 1 文件存在 // 2 读入的内容不是全部 int nRet = FileUtil.ReadTextFileContent(strFileName, -1, out strTemplate, out encoding, out strError); if (nRet != 1) return -1; return 0; } #if NO // 根据时间字符串得到 子目录名 // 2014 --> 2014 // 201401 --> 2014/01 // 20140101 --> 2014/01/01 static string GetSubDirName(string strTime) { if (string.IsNullOrEmpty(strTime) == true) return ""; if (strTime.Length == 4) return strTime; if (strTime.Length == 6) return strTime.Insert(4, "/"); if (strTime.Length == 8) return strTime.Insert(6, "/").Insert(4, "/"); return strTime; } #endif // 根据时间字符串得到 子目录名 // 2014 --> 2014 // 201401 --> 2014/201401 // 20140101 --> 2014/201401/20140101 static string GetSubDirName(string strTime) { if (string.IsNullOrEmpty(strTime) == true) return ""; if (strTime.Length == 4) return strTime; if (strTime.Length == 6) return strTime.Substring(0, 4) + "/" + strTime; if (strTime.Length == 8) return strTime.Substring(0, 4) + "/" + strTime.Substring(0, 6) + "/" + strTime; return strTime; } #if NO Hashtable _doneTable = new Hashtable(); int LoadDoneTable( out string strError) { strError = ""; this._doneTable.Clear(); string strBreakPointFileName = Path.Combine(Program.MainForm.UserDir, "dailyreport_breakpoint.txt"); if (File.Exists(strBreakPointFileName) == false) return 0; using (StreamReader sr = new StreamReader(strBreakPointFileName, Encoding.UTF8)) { for (; ; ) { string strText = sr.ReadLine(); if (strText == null) break; this._doneTable[strText] = true; } } return 0; } int SaveDoneTable( bool bDelete, out string strError) { strError = ""; string strBreakPointFileName = Path.Combine(Program.MainForm.UserDir, "dailyreport_breakpoint.txt"); if (bDelete == true) { this._doneTable.Clear(); File.Delete(strBreakPointFileName); return 0; } using (StreamWriter sw = new StreamWriter(strBreakPointFileName, false, Encoding.UTF8)) { foreach (string key in this._doneTable.Keys) { sw.WriteLine(key); } } this._doneTable.Clear(); return 0; } #endif // 获得适合用作报表名或文件名 的 地点名称字符串 static string GetLocationCaption(string strText) { if (string.IsNullOrEmpty(strText) == true) return "[空]"; if (strText[strText.Length - 1] == '/') return strText.Substring(0, strText.Length - 1) + "[全部]"; return strText; } // 分管的管部馆藏地点 cache ObjectCache<List<string>> _libraryLocationCache = new ObjectCache<List<string>>(); // 创建一个特定时间段(一个分馆)的若干报表 // 要讲创建好的报表写入相应目录的 index.xml 中 // parameters: // strTimeType 时间单位类型。 year month week day 之一 // times 本轮的全部时间字符串。strTime 一定在其中。通过 times 和 strTime,能看出 strTime 时间是不是数组最后一个元素 // return: // -1 出错 // 0 没有任何匹配的报表 // 1 成功处理 int CreateOneTimeReports( string strTimeType, OneTime time, bool bTailTime, // List<OneTime> times, string strLibraryCode, List<string> report_names, List<BiblioDbFromInfo> class_styles, out string strError) { strError = ""; int nRet = 0; #if NO bool bTailTime = false; // 是否为本轮最后一个(非探测)时间 if (times.IndexOf(time) == times.Count - 1) { if (time.Detect == false) bTailTime = true; } #endif // 特定分馆的报表输出目录 // string strReportsDir = Path.Combine(Program.MainForm.UserDir, "reports/" + (string.IsNullOrEmpty(strLibraryCode) == true ? "global" : strLibraryCode)); string strReportsDir = GetReportOutputDir(strLibraryCode); PathUtil.TryCreateDir(strReportsDir); // 输出文件目录 // string strOutputDir = Path.Combine(strReportsDir, time.Time); // 延迟到创建表格的时候创建子目录 string strOutputDir = Path.Combine(strReportsDir, GetValidPathString(GetSubDirName(time.Time))); // 看看目录是否已经存在 if (time.Detect) { DirectoryInfo di = new DirectoryInfo(strOutputDir); if (di.Exists == true) return 0; } #if NOOOO List<string> class_styles = new List<string>(); // 获得所有分类号检索途径 style nRet = GetClassFromStyles(out class_styles, out strError); if (nRet == -1) return -1; #if NO class_styles.Add("clc"); class_styles.Add("hnb"); #endif #endif #if NO List<BiblioDbFromInfo> class_styles = new List<BiblioDbFromInfo>(); // 获得所有分类号检索途径 style nRet = GetClassFromStyles(out class_styles, out strError); if (nRet == -1) return -1; #endif //foreach (string strLibraryCode in librarycodes) //{ XmlNode nodeLibrary = this._cfg.GetLibraryNode(strLibraryCode); if (nodeLibrary == null) { strError = "在配置文件中没有找到馆代码为 '" + strLibraryCode + "' 的 <library> 元素"; return -1; } string strTemplate = ""; nRet = LoadHtmlTemplate(nodeLibrary, out strTemplate, out strError); if (nRet == -1) return -1; this._cssTemplate = strTemplate; List<XmlNode> report_nodes = new List<XmlNode>(); if (report_names != null) { foreach (string strName in report_names) { XmlNode node = nodeLibrary.SelectSingleNode("reports/report[@name='" + strName + "']"); if (node == null) { continue; #if NO strError = "在配置文件中没有找到馆代码为 '" + strLibraryCode + "' 的 <library> 元素下的 name 属性值为 '"+strName+"' 的 report 元素"; return -1; // TODO: 出现 MessageBox 警告,但可以选择继续 #endif } report_nodes.Add(node); } if (report_nodes.Count == 0) return 0; // 没有任何匹配的报表 } else { XmlNodeList nodes = nodeLibrary.SelectNodes("reports/report"); if (nodes.Count == 0) return 0; // 这个分馆 当前没有配置任何报表 foreach (XmlNode node in nodes) { report_nodes.Add(node); } } foreach (XmlNode node in report_nodes) { if (this.InvokeRequired == false) Application.DoEvents(); if (stop != null && stop.State != 0) { strError = "中断"; return -1; } string strName = DomUtil.GetAttr(node, "name"); string strReportType = DomUtil.GetAttr(node, "type"); string strCfgFile = DomUtil.GetAttr(node, "cfgFile"); string strNameTable = DomUtil.GetAttr(node, "nameTable"); string strFreq = DomUtil.GetAttr(node, "frequency"); #if NO ReportConfigStruct config = null; // 从报表配置文件中获得各种配置信息 // return: // -1 出错 // 0 没有找到配置文件 // 1 成功 nRet = ReportDefForm.GetReportConfig(strCfgFile, out config, out strError); if (nRet == -1) return -1; #endif ReportWriter writer = null; nRet = GetReportWriter(strCfgFile, out writer, out strError); if (nRet == -1) return -1; // *** 判断频率 if (report_names == null) { if (StringUtil.IsInList(strTimeType, strFreq) == false) continue; } // 在指定了报表名称列表的情况下,频率不再筛选 // 判断新鲜程度。只有本轮最后一次才创建报表 #if NO if (config.Fresh == true && bTailTime == false) continue; #endif if (writer.GetFresh() == true && bTailTime == false) continue; Hashtable macro_table = new Hashtable(); macro_table["%library%"] = strLibraryCode; string strOutputFileName = Path.Combine(strOutputDir, Guid.NewGuid().ToString() + ".rml"); string strDoneName = strLibraryCode + "|" + time.Time + "|" + strName + "|" + strReportType + "|"; #if NO if (this._doneTable.ContainsKey(strDoneName) == true) continue; // 前次已经做过了 #endif int nAdd = 0; // 0 表示什么也不做。 1表示要加入 -1 表示要删除 if (strReportType == "102" || strReportType == "9102") { // *** 102 // 按照指定的单位名称列表,列出借书册数 nRet = Create_102_report(strLibraryCode, time.Time, strCfgFile, // "选定的部门", // 例如: 各年级 macro_table, strNameTable, strOutputFileName, strReportType, out strError); if (nRet == -1) return -1; if (nRet == 0) nAdd = -1; else if (nRet == 1) nAdd = 1; } else if (strReportType == "101" || strReportType == "9101" || strReportType == "111" || strReportType == "9111" || strReportType == "121" || strReportType == "9121" || strReportType == "122" || strReportType == "9122" || strReportType == "141") { nRet = Create_1XX_report(strLibraryCode, time.Time, strCfgFile, macro_table, strOutputFileName, strReportType, out strError); if (nRet == -1) return -1; if (nRet == 0) nAdd = -1; else if (nRet == 1) nAdd = 1; } else if (strReportType == "131" || strReportType == "9131") { string str131Dir = Path.Combine(strOutputDir, "table_" + strReportType); // 这是创建到一个子目录(会在子目录中创建很多文件和下级目录),而不是输出到一个文件 nRet = Create_131_report(strLibraryCode, time.Time, strCfgFile, macro_table, str131Dir, strReportType, out strError); if (nRet == -1) return -1; // if (nRet == 1) { // 将 131 目录事项写入 index.xml nRet = WriteIndexXml( strTimeType, time.Time, strName, "", // strReportsDir, str131Dir, strReportType, nRet == 1, out strError); if (nRet == -1) return -1; } } else if (strReportType == "201" || strReportType == "9201" || strReportType == "202" || strReportType == "9202" || strReportType == "212" || strReportType == "9212" || strReportType == "213") // begin of 2xx { if ((strReportType == "212" || strReportType == "9212") && class_styles.Count == 0) continue; if (strReportType == "213") continue; // 213 表已经被废止,其原有功能被合并到 212 表 // 获得分馆的所有馆藏地点 List<string> locations = null; locations = this._libraryLocationCache.FindObject(strLibraryCode); if (locations == null) { nRet = GetAllItemLocations( strLibraryCode, true, out locations, out strError); if (nRet == -1) return -1; this._libraryLocationCache.SetObject(strLibraryCode, locations); } int iLocation = 0; foreach (string strLocation in locations) { if (this.InvokeRequired == false) Application.DoEvents(); if (stop != null && stop.State != 0) { strError = "中断"; return -1; } this.ShowMessage("正在为馆藏地 '" + strLocation + "' 创建 " + strReportType + " 报表 (" + (iLocation + 1) + "/" + locations.Count + ")"); macro_table["%location%"] = GetLocationCaption(strLocation); // 这里稍微特殊一点,循环要写入多个输出文件 if (string.IsNullOrEmpty(strOutputFileName) == true) strOutputFileName = Path.Combine(strOutputDir, Guid.NewGuid().ToString() + ".rml"); if (strReportType == "201" || strReportType == "9201") { nRet = Create_201_report(strLocation, time.Time, strCfgFile, macro_table, strOutputFileName, strReportType, out strError); if (nRet == -1) return -1; } else if (strReportType == "202" || strReportType == "9202") { nRet = Create_202_report(strLocation, time.Time, strCfgFile, macro_table, strOutputFileName, strReportType, out strError); if (nRet == -1) return -1; } else if (strReportType == "212" || strReportType == "9212" || strReportType == "213" || strReportType == "9213") { // List<string> names = StringUtil.SplitList(strNameTable); List<OneClassType> class_table = null; nRet = OneClassType.BuildClassTypes(strNameTable, out class_table, out strError); if (nRet == -1) { strError = "报表类型 '" + strReportType + "' 的名字表定义不合法: " + strError; return -1; } foreach (BiblioDbFromInfo style in class_styles) { if (this.InvokeRequired == false) Application.DoEvents(); #if NO if (names.Count > 0) { // 只处理设定的那些 class styles if (names.IndexOf(style.Style) == -1) continue; } #endif OneClassType current_type = null; if (class_table.Count > 0) { // 只处理设定的那些 class styles int index = OneClassType.IndexOf(class_table, style.Style); if (index == -1) continue; current_type = class_table[index]; } // 这里稍微特殊一点,循环要写入多个输出文件 if (string.IsNullOrEmpty(strOutputFileName) == true) strOutputFileName = Path.Combine(strOutputDir, Guid.NewGuid().ToString() + ".rml"); nRet = Create_212_report(strLocation, style.Style, style.Caption, time.Time, strCfgFile, macro_table, current_type == null ? null : current_type.Filters, strOutputFileName, strReportType, out strError); if (nRet == -1) return -1; // if (nRet == 1) { // 写入 index.xml nRet = WriteIndexXml( strTimeType, time.Time, GetLocationCaption(strLocation) + "-" + style.Caption, // 把名字区别开。否则写入 <report> 会重叠覆盖 strName, // strReportsDir, strOutputFileName, strReportType, nRet == 1, out strError); if (nRet == -1) return -1; strOutputFileName = ""; } } } if (File.Exists(strOutputFileName) == true) { // 写入 index.xml nRet = WriteIndexXml( strTimeType, time.Time, GetLocationCaption(strLocation), // 把名字区别开。否则写入 <report> 会重叠覆盖 strName, // strReportsDir, strOutputFileName, strReportType, true, out strError); if (nRet == -1) return -1; strOutputFileName = ""; } iLocation++; } this.ClearMessage(); // TODO: 总的馆藏地点还要来一次 } // end 2xx else if (strReportType == "301" || strReportType == "302") // begin of 3xx { // 获得分馆的所有馆藏地点 List<string> locations = null; locations = this._libraryLocationCache.FindObject(strLibraryCode); if (locations == null) { nRet = GetAllItemLocations( strLibraryCode, true, out locations, out strError); if (nRet == -1) return -1; this._libraryLocationCache.SetObject(strLibraryCode, locations); } int iLocation = 0; foreach (string strLocation in locations) { if (this.InvokeRequired == false) Application.DoEvents(); if (stop != null && stop.State != 0) { strError = "中断"; return -1; } this.ShowMessage("正在为馆藏地 '" + strLocation + "' 创建 " + strReportType + " 报表 (" + (iLocation + 1) + "/" + locations.Count + ")"); macro_table["%location%"] = GetLocationCaption(strLocation); // 这里稍微特殊一点,循环要写入多个输出文件 if (string.IsNullOrEmpty(strOutputFileName) == true) strOutputFileName = Path.Combine(strOutputDir, Guid.NewGuid().ToString() + ".rml"); if (strReportType == "301" || strReportType == "302") { // List<string> names = StringUtil.SplitList(strNameTable); List<OneClassType> class_table = null; nRet = OneClassType.BuildClassTypes(strNameTable, out class_table, out strError); if (nRet == -1) { strError = "报表类型 '" + strReportType + "' 的名字表定义不合法: " + strError; return -1; } foreach (BiblioDbFromInfo style in class_styles) { if (this.InvokeRequired == false) Application.DoEvents(); if (stop != null && stop.State != 0) { strError = "中断"; return -1; } #if NO if (names.Count > 0) { // 只处理设定的那些 class styles if (names.IndexOf(style.Style) == -1) continue; } #endif OneClassType current_type = null; if (class_table.Count > 0) { // 只处理设定的那些 class styles int index = OneClassType.IndexOf(class_table, style.Style); if (index == -1) continue; current_type = class_table[index]; } // 这里稍微特殊一点,循环要写入多个输出文件 if (string.IsNullOrEmpty(strOutputFileName) == true) strOutputFileName = Path.Combine(strOutputDir, Guid.NewGuid().ToString() + ".rml"); if (strReportType == "301") nRet = Create_301_report(strLocation, style.Style, style.Caption, time.Time, strCfgFile, macro_table, current_type == null ? null : current_type.Filters, strOutputFileName, out strError); else if (strReportType == "302") nRet = Create_302_report(strLocation, style.Style, style.Caption, time.Time, strCfgFile, macro_table, current_type == null ? null : current_type.Filters, strOutputFileName, out strError); if (nRet == -1) return -1; // if (nRet == 1) { // 写入 index.xml nRet = WriteIndexXml( strTimeType, time.Time, GetLocationCaption(strLocation) + "-" + style.Caption, // 把名字区别开。否则写入 <report> 会重叠覆盖 strName, // strReportsDir, strOutputFileName, strReportType, nRet == 1, out strError); if (nRet == -1) return -1; strOutputFileName = ""; } } } if (File.Exists(strOutputFileName) == true) { // 写入 index.xml nRet = WriteIndexXml( strTimeType, time.Time, GetLocationCaption(strLocation), // 把名字区别开。否则写入 <report> 会重叠覆盖 strName, // strReportsDir, strOutputFileName, strReportType, true, out strError); if (nRet == -1) return -1; strOutputFileName = ""; } iLocation++; } this.ClearMessage(); // TODO: 总的馆藏地点还要来一次 } // end 3xx else if (strReportType == "411" || strReportType == "412" || strReportType == "421" || strReportType == "422" || strReportType == "431" || strReportType == "432" || strReportType == "441" || strReportType == "442" || strReportType == "443" || strReportType == "451" || strReportType == "452" || strReportType == "471" || strReportType == "472" || strReportType == "481" || strReportType == "482" || strReportType == "491" || strReportType == "492" ) { nRet = Create_4XX_report(strLibraryCode, time.Time, strCfgFile, macro_table, strOutputFileName, strReportType, out strError); if (nRet == -1) return -1; if (nRet == 0) nAdd = -1; else if (nRet == 1) nAdd = 1; } else if (strReportType == "493") { #if NO // 这里稍微特殊一点,循环要写入多个输出文件 if (string.IsNullOrEmpty(strOutputFileName) == true) strOutputFileName = Path.Combine(strOutputDir, Guid.NewGuid().ToString() + ".rml"); #endif List<OneClassType> class_table = null; nRet = OneClassType.BuildClassTypes(strNameTable, out class_table, out strError); if (nRet == -1) { strError = "报表类型 '" + strReportType + "' 的名字表定义不合法: " + strError; return -1; } foreach (BiblioDbFromInfo style in class_styles) { if (this.InvokeRequired == false) Application.DoEvents(); if (stop != null && stop.State != 0) { strError = "中断"; return -1; } OneClassType current_type = null; if (class_table.Count > 0) { // 只处理设定的那些 class styles int index = OneClassType.IndexOf(class_table, style.Style); if (index == -1) continue; current_type = class_table[index]; } // 这里稍微特殊一点,循环要写入多个输出文件 if (string.IsNullOrEmpty(strOutputFileName) == true) strOutputFileName = Path.Combine(strOutputDir, Guid.NewGuid().ToString() + ".rml"); nRet = Create_493_report( strLibraryCode, style.Style, style.Caption, time.Time, strCfgFile, macro_table, current_type == null ? null : current_type.Filters, strOutputFileName, out strError); if (nRet == -1) return -1; // if (nRet == 1) { // 写入 index.xml nRet = WriteIndexXml( strTimeType, time.Time, style.Caption, // 把名字区别开。否则写入 <report> 会重叠覆盖 strName, // strReportsDir, strOutputFileName, strReportType, nRet == 1, out strError); if (nRet == -1) return -1; strOutputFileName = ""; } } } else { strError = "未知的 strReportType '" + strReportType + "'"; return -1; } #if NO this._doneTable[strDoneName] = true; #endif if (string.IsNullOrEmpty(strOutputFileName) == false && nAdd != 0) { if (nAdd == 1 && File.Exists(strOutputFileName) == false) { } else { // 写入 index.xml nRet = WriteIndexXml( strTimeType, time.Time, strName, "", // strReportsDir, strOutputFileName, strReportType, nAdd == 1, out strError); if (nRet == -1) return -1; } } } // } return 1; } #region index.xml #if NO XmlDocument _indexDom = null; // index.xml 文件的 DOM 对象 string _strIndexXmlFileName = ""; // index.xml 文件的文件名全路径 #endif #if NO // 保存 index.xml 的 DOM 到文件。或者用于开始处理前的初始化 void CloseIndexXmlDocument() { if (string.IsNullOrEmpty(_strIndexXmlFileName) == false) { // 保存上一个文件 Debug.Assert(_indexDom != null, ""); _indexDom.Save(_strIndexXmlFileName); File.SetAttributes(_strIndexXmlFileName, FileAttributes.Archive); _indexDom = null; _strIndexXmlFileName = ""; } } #endif public static void RemoveArchiveAttribute(string strFileName) { // File.SetAttributes(strFileName, FileAttributes.Normal); } static bool IsEmpty(XmlDocument dom) { if (dom.DocumentElement.ChildNodes.Count == 0 && dom.DocumentElement.Name != "dir" && dom.DocumentElement.Name != "report") return true; return false; } ObjectCache<XmlDocument> _indexCache = new ObjectCache<XmlDocument>(); // 收缩 cache 尺寸 // parameters: // bShrinkAll 是否全部收缩 void ShrinkIndexCache(bool bShrinkAll) { if (this._indexCache.Count > 10 || bShrinkAll == true) { foreach (string filename in this._indexCache.Keys) { XmlDocument dom = this._indexCache.FindObject(filename); if (dom == null) { Debug.Assert(false, ""); continue; } // string strHashCode = dom.GetHashCode().ToString(); if (IsEmpty(dom) == true) { // 2014/6/12 // 如果 DOM 为空,则要删除物理文件 try { File.Delete(filename); } catch (DirectoryNotFoundException) { } } else { try { dom.Save(filename); } catch (DirectoryNotFoundException) { PathUtil.TryCreateDir(Path.GetDirectoryName(filename)); dom.Save(filename); } } } this._indexCache.Clear(); } } // 将一个统计文件条目写入到 index.xml 的 DOM 中 // 注:要确保每个报表的名字 strTableName 是不同的。如果同一报表要在不同条件下输出多次,需要把条件字符串也加入到名字中 // parameters: // strOutputDir 报表输出目录。例如 c:\users\administrator\dp2circulation_v2\reports int WriteIndexXml( string strTimeType, string strTime, string strTableName, // string strOutputDir, string strGroupName, string strReportFileName, string strReportType, bool bAdd, out string strError) { strError = ""; // 这里决定在分馆所述的目录内,如何划分 index.xml 文件的层级和个数 string strOutputDir = Path.GetDirectoryName(strReportFileName); string strFileName = Path.Combine(strOutputDir, "index.xml"); XmlDocument index_dom = this._indexCache.FindObject(strFileName); if (index_dom == null && bAdd == false) { try { File.Delete(strReportFileName); } catch (DirectoryNotFoundException) { } return 0; } if (index_dom == null) { index_dom = new XmlDocument(); if (File.Exists(strFileName) == true) { try { index_dom.Load(strFileName); } catch (Exception ex) { strError = "装入文件 " + strFileName + " 时出错: " + ex.Message; return -1; } } else { index_dom.LoadXml("<root />"); } this._indexCache.SetObject(strFileName, index_dom); } // string strHashCode = index_dom.GetHashCode().ToString(); // 根据时间类型创建一个 index.xml 中的 item 元素 XmlNode item = null; if (strReportType == "131" || strReportType == "9131") { item = CreateDirNode(index_dom.DocumentElement, strTableName + "-" + strReportType, bAdd ? 1 : -1); if (bAdd == false) return 0; Debug.Assert(item != null, ""); string strNewFileName = "." + strReportFileName.Substring(strOutputDir.Length); DomUtil.SetAttr(item, "link", strNewFileName.Replace("\\", "/")); } else { if (string.IsNullOrEmpty(strGroupName) == false) { item = CreateReportNode(index_dom.DocumentElement, strGroupName + "-" + strReportType, strTableName, bAdd); } else { item = CreateReportNode(index_dom.DocumentElement, strGroupName, strTableName + "-" + strReportType, bAdd); } if (bAdd == false) { // TODO: 还需要删除 index.xml 中条目指向的原有文件 try { File.Delete(strReportFileName); } catch (DirectoryNotFoundException) { } return 0; } Debug.Assert(item != null, ""); /* * 文件名不能包含任何以下字符:\ / : * ?"< > | * 对于命名的文件、 文件夹或快捷方式是有效的字符包括字母 (A-Z) 和数字 (0-9),再加上下列特殊字符的任意组合: ^ Accent circumflex (caret) & Ampersand ' Apostrophe (single quotation mark) @ At sign { Brace left } Brace right [ Bracket opening ] Bracket closing , Comma $ Dollar sign = Equal sign ! Exclamation point - Hyphen # Number sign ( Parenthesis opening ) Parenthesis closing % Percent . Period + Plus ~ Tilde _ Underscore * */ string strName = DomUtil.GetAttr(item, "name").Replace("/", "+"); Debug.Assert(strGroupName.IndexOf("/") == -1, ""); Debug.Assert(strName.IndexOf("|") == -1, ""); // 将文件名改名 string strFileName1 = Path.Combine(Path.GetDirectoryName(strReportFileName), GetValidPathString((string.IsNullOrEmpty(strGroupName) == false ? strGroupName + "-" : "") + strName) + Path.GetExtension(strReportFileName)); if (File.Exists(strFileName1) == true) File.Delete(strFileName1); #if NO FileAttributes attr = File.GetAttributes(strReportHtmlFileName); #endif File.Move(strReportFileName, strFileName1); strReportFileName = strFileName1; #if NO FileAttributes attr1 = File.GetAttributes(strReportHtmlFileName); Debug.Assert(attr == attr1, ""); #endif string strNewFileName = "." + strReportFileName.Substring(strOutputDir.Length); // 创建 .html 文件 if ((this._fileType & FileType.HTML) != 0) { string strHtmlFileName = Path.Combine(Path.GetDirectoryName(strReportFileName), Path.GetFileNameWithoutExtension(strReportFileName) + ".html"); int nRet = Report.RmlToHtml(strReportFileName, strHtmlFileName, this._cssTemplate, out strError); if (nRet == -1) return -1; RemoveArchiveAttribute(strHtmlFileName); } // 创建 Excel 文件 if ((this._fileType & FileType.Excel) != 0) { string strExcelFileName = Path.Combine(Path.GetDirectoryName(strReportFileName), Path.GetFileNameWithoutExtension(strReportFileName) + ".xlsx"); int nRet = Report.RmlToExcel(strReportFileName, strExcelFileName, out strError); if (nRet == -1) return -1; RemoveArchiveAttribute(strExcelFileName); } // 删除以前的对照关系 string strOldFileName = DomUtil.GetAttr(item, "link"); if (string.IsNullOrEmpty(strOldFileName) == false) // && PathUtil.IsEqual(strOldFileName, strHtmlFileName) == false { string strOldPhysicalPath = GetRealPath(strOutputDir, strOldFileName); if (PathUtil.IsEqual(strOldPhysicalPath, strReportFileName) == false && File.Exists(strOldPhysicalPath) == true) { try { File.Delete(strOldPhysicalPath); } catch { } } } DomUtil.SetAttr(item, "link", strNewFileName.Replace("\\", "/")); #if DEBUG // 检查文件是否存在 if (File.Exists(strReportFileName) == false) { strError = strTime + " " + strTableName + " 的文件 '" + strReportFileName + "' 不存在"; return -1; } #endif } // _indexDom.Save(strFileName); ShrinkIndexCache(false); #if NO #if DEBUG FileAttributes attr1 = File.GetAttributes(strFileName); Debug.Assert((attr1 & FileAttributes.Archive) == FileAttributes.Archive, ""); #endif #endif // File.SetAttributes(strFileName, FileAttributes.Archive); return 0; } // 获得文件的物理路径 // parameters: // strFileName 为 "./2013/some" 或者 "c"\\dir\、file" 这样的 static string GetRealPath(string strOutputDir, string strFileName) { if (StringUtil.HasHead(strFileName, "./") == true || StringUtil.HasHead(strFileName, ".\\") == true) { return strOutputDir + strFileName.Substring(1); } return strFileName; } static XmlElement NewLeafElement( XmlNode parent, string strReportName, string strReportType) { string strElementName = "report"; if (strReportType == "131" || strReportType == "9131") strElementName = "dir"; XmlNode item = parent.SelectSingleNode(strElementName + "[@name='" + strReportName + "']"); if (item == null) { item = parent.OwnerDocument.CreateElement(strElementName); parent.AppendChild(item); DomUtil.SetAttr(item, "name", strReportName); DomUtil.SetAttr(item, "type", strReportType); } return item as XmlElement; } // 根据时间类型创建一个 index.xml 中的 report(或dir) 元素 // 要根据时间,创建一些列 dir 父元素。返回前已经写好 name 和 type 属性了 static XmlNode CreateItemNode(XmlNode root, string strTimeType, string strTime, string strReportName, string strReportType) { Debug.Assert(strTime.Length >= 4, ""); // 2014/6/7 if (strTimeType == "free") { string strDirName = strTime; XmlNode new_node = root.SelectSingleNode("dir[@name='" + strDirName + "']"); if (new_node == null) { new_node = root.OwnerDocument.CreateElement("dir"); root.AppendChild(new_node); DomUtil.SetAttr(new_node, "name", strDirName); DomUtil.SetAttr(new_node, "type", "free"); } return NewLeafElement(new_node, strReportName, strReportType); } string strYear = strTime.Substring(0, 4); XmlNode year = root.SelectSingleNode("dir[@name='" + strYear + "']"); if (year == null) { year = root.OwnerDocument.CreateElement("dir"); root.AppendChild(year); DomUtil.SetAttr(year, "name", strYear); DomUtil.SetAttr(year, "type", "year"); } if (strTimeType == "year") { #if NO XmlNode item = year.SelectSingleNode("report[@name='" + strReportName + "']"); if (item == null) { item = year.OwnerDocument.CreateElement("report"); year.AppendChild(item); DomUtil.SetAttr(item, "name", strReportName); } return item; #endif return NewLeafElement(year, strReportName, strReportType); } Debug.Assert(strTime.Length >= 6, ""); string strMonth = strTime.Substring(0, 6); XmlNode month = year.SelectSingleNode("dir[@name='" + strMonth + "']"); if (month == null) { month = root.OwnerDocument.CreateElement("dir"); year.AppendChild(month); DomUtil.SetAttr(month, "name", strMonth); DomUtil.SetAttr(month, "type", "month"); } if (strTimeType == "month") { #if NO XmlNode item = month.SelectSingleNode("report[@name='" + strReportName + "']"); if (item == null) { item = month.OwnerDocument.CreateElement("report"); month.AppendChild(item); DomUtil.SetAttr(item, "name", strReportName); } return item; #endif return NewLeafElement(month, strReportName, strReportType); } Debug.Assert(strTime.Length >= 8, ""); string strDay = strTime.Substring(0, 8); XmlNode day = month.SelectSingleNode("dir[@name='" + strDay + "']"); if (day == null) { day = root.OwnerDocument.CreateElement("dir"); month.AppendChild(day); DomUtil.SetAttr(day, "name", strDay); DomUtil.SetAttr(day, "type", "day"); } if (strTimeType == "day") { #if NO XmlNode item = day.SelectSingleNode("report[@name='" + strReportName + "']"); if (item == null) { item = day.OwnerDocument.CreateElement("report"); day.AppendChild(item); DomUtil.SetAttr(item, "name", strReportName); } return item; #endif return NewLeafElement(day, strReportName, strReportType); } throw new ArgumentException("未知的 strTimeType 值 '" + strTimeType + "'", "strTimeType"); } // 根据 index.xml 文件创建 index.html 文件 // return: // -1 出错 // 0 没有创建。因为 index.xml 文件不存在 // 1 创建成功 int CreateIndexHtmlFile(string strIndexXmlFileName, string strIndexHtmlFileName, out string strError) { strError = ""; if (File.Exists(strIndexXmlFileName) == false) return 0; XmlDocument dom = new XmlDocument(); try { dom.Load(strIndexXmlFileName); } catch (Exception ex) { strError = "装入文件 " + strIndexXmlFileName + " 时出错: " + ex.Message; return -1; } StringBuilder text = new StringBuilder(4096); text.Append("<html><body>"); XmlNode dir = dom.DocumentElement; // TODO: 也可以用 <dir> 元素的上级 OutputHtml(dir as XmlElement, text); text.Append("</body></html>"); WriteToOutputFile(strIndexHtmlFileName, text.ToString(), Encoding.UTF8); // index.html 不要上传 // File.SetAttributes(strIndexHtmlFileName, FileAttributes.Archive); return 1; } string _cssTemplate = ""; // TODO: 需要用缓存优化 // 将一个统计文件条目写入到 131 子目录中的 index.xml 的 DOM 中 // parameters: // strOutputDir index.xml 所在目录 int Write_131_IndexXml( string strDepartment, string strPersonName, string strPatronBarcode, string strOutputDir, string strReportFileName, string strReportType, out string strError) { strError = ""; string strFileName = Path.Combine(strOutputDir, "index.xml"); XmlDocument index_dom = this._indexCache.FindObject(strFileName); if (index_dom == null) { index_dom = new XmlDocument(); if (File.Exists(strFileName) == true) { try { index_dom.Load(strFileName); } catch (Exception ex) { strError = "装入文件 " + strFileName + " 时出错: " + ex.Message; return -1; } } else { index_dom.LoadXml("<root />"); } this._indexCache.SetObject(strFileName, index_dom); } // 创建一个 index.xml 中的 item 元素 XmlNode item = Create_131_ItemNode(index_dom.DocumentElement, strDepartment, strPersonName + "-" + strPatronBarcode); Debug.Assert(item != null, ""); DomUtil.SetAttr(item, "type", strReportType); string strNewFileName = "." + strReportFileName.Substring(strOutputDir.Length); // 创建 .html 文件 if ((this._fileType & FileType.HTML) != 0) { string strHtmlFileName = Path.Combine(Path.GetDirectoryName(strReportFileName), Path.GetFileNameWithoutExtension(strReportFileName) + ".html"); int nRet = Report.RmlToHtml(strReportFileName, strHtmlFileName, this._cssTemplate, out strError); if (nRet == -1) return -1; RemoveArchiveAttribute(strHtmlFileName); } // 创建 Excel 文件 if ((this._fileType & FileType.Excel) != 0) { string strExcelFileName = Path.Combine(Path.GetDirectoryName(strReportFileName), Path.GetFileNameWithoutExtension(strReportFileName) + ".xlsx"); int nRet = Report.RmlToExcel(strReportFileName, strExcelFileName, out strError); if (nRet == -1) return -1; RemoveArchiveAttribute(strExcelFileName); } // 删除以前的对照关系 string strOldFileName = DomUtil.GetAttr(item, "link"); if (string.IsNullOrEmpty(strOldFileName) == false) // && PathUtil.IsEqual(strOldFileName, strHtmlFileName) == false { string strOldPhysicalPath = GetRealPath(strOutputDir, strOldFileName); if (PathUtil.IsEqual(strOldPhysicalPath, strReportFileName) == false && File.Exists(strOldPhysicalPath) == true) { try { File.Delete(strOldPhysicalPath); } catch { } } } DomUtil.SetAttr(item, "link", strNewFileName.Replace("\\", "/")); #if DEBUG // 检查文件是否存在 if (File.Exists(strReportFileName) == false) { strError = "文件 '" + strReportFileName + "' 不存在"; return -1; } #endif // index_dom.Save(strFileName); ShrinkIndexCache(false); // 131 目录的 index.html 不要上传 // File.SetAttributes(strFileName, FileAttributes.Archive); return 0; } // 创建一个 index.xml 中的 report 元素 static XmlNode CreateReportNode(XmlNode root, string strGroupName, string strReportName, bool bAdd) { XmlNode start = root; if (string.IsNullOrEmpty(strGroupName) == false) { XmlNode group = null; if (bAdd == false) { group = CreateDirNode(root, strGroupName, 0); if (group == null) return null; } else { group = CreateDirNode(root, strGroupName, 1); DomUtil.SetAttr(group, "type", "group"); } start = group; } XmlNode item = start.SelectSingleNode("report[@name='" + strReportName + "']"); if (bAdd == false) { if (item != null) item.ParentNode.RemoveChild(item); return item; } if (item == null) { item = start.OwnerDocument.CreateElement("report"); start.AppendChild(item); DomUtil.SetAttr(item, "name", strReportName); } return item; } // parameters: // nAdd -1: delete 0: detect 1: add static XmlNode CreateDirNode(XmlNode root, string strDirName, int nAdd) { XmlNode dir = root.SelectSingleNode("dir[@name='" + strDirName + "']"); if (nAdd == 0) return dir; if (nAdd == -1) { if (dir != null) dir.ParentNode.RemoveChild(dir); return dir; } Debug.Assert(nAdd == 1, ""); if (dir == null) { dir = root.OwnerDocument.CreateElement("dir"); root.AppendChild(dir); DomUtil.SetAttr(dir, "name", strDirName); } return dir; } // 创建一个 131 类型的 index.xml 中的 item 元素 static XmlNode Create_131_ItemNode(XmlNode root, string strDepartment, string strReportName) { XmlNode department = null; if (string.IsNullOrEmpty(strDepartment) == false) { department = root.SelectSingleNode("dir[@name='" + strDepartment + "']"); if (department == null) { department = root.OwnerDocument.CreateElement("dir"); root.AppendChild(department); DomUtil.SetAttr(department, "name", strDepartment); } } else { department = root; // strDepartment 如果为空,则不用创建 dir 元素了 } XmlNode item = department.SelectSingleNode("report[@name='" + strReportName + "']"); if (item == null) { item = department.OwnerDocument.CreateElement("report"); department.AppendChild(item); DomUtil.SetAttr(item, "name", strReportName); } return item; } static string GetDisplayTimeString(string strTime) { if (strTime.Length == 8) return strTime.Substring(0, 4) + "." + strTime.Substring(4, 2) + "." + strTime.Substring(6, 2); if (strTime.Length == 6) return strTime.Substring(0, 4) + "." + strTime.Substring(4, 2); return strTime; } void OutputHtml( XmlElement dir, StringBuilder text) { { string strLink = dir.GetAttribute("link"); string strDirName = GetDisplayTimeString(dir.GetAttribute("name")); if (string.IsNullOrEmpty(strLink) == true) { text.Append("<div>"); text.Append(HttpUtility.HtmlEncode(strDirName)); text.Append("</div>"); } else { text.Append("<li>"); text.Append("<a href='" + strLink + "' >"); text.Append(HttpUtility.HtmlEncode(strDirName) + " ..."); text.Append("</a>"); text.Append("</li>"); return; } } text.Append("<ul>"); XmlNodeList reports = dir.SelectNodes("report"); foreach (XmlElement report in reports) { string strName = report.GetAttribute("name"); string strLink = report.GetAttribute("link"); // link 加工为 .html 形态 if ((this._fileType & FileType.HTML) != 0) { strLink = Path.Combine(Path.GetDirectoryName(strLink), Path.GetFileNameWithoutExtension(strLink) + ".html"); } text.Append("<li>"); text.Append("<a href='" + strLink + "' >"); text.Append(HttpUtility.HtmlEncode(strName)); text.Append("</a>"); text.Append("</li>"); } XmlNodeList dirs = dir.SelectNodes("dir"); foreach (XmlElement sub_dir in dirs) { OutputHtml(sub_dir, text); } text.Append("</ul>"); } #endregion private void toolStripButton_setReportStartDay_Click(object sender, EventArgs e) { // string strError = ""; // 这个日期是上次处理完成的那一天的后一天,也就是说下次处理,从这天开始即可 string strLastDate = Program.MainForm.AppInfo.GetString(GetReportSection(), "daily_report_end_date", "20130101"); REDO: strLastDate = InputDlg.GetInput( this, "设置报表创建起点日期", "报表创建起点日期: ", strLastDate, Program.MainForm.DefaultFont); if (strLastDate == null) return; if (string.IsNullOrEmpty(strLastDate) == true || strLastDate.Length != 8 || StringUtil.IsNumber(strLastDate) == false) { MessageBox.Show(this, "所输入的日期字符串 '" + strLastDate + "' 不合法,应该是 8 字符的时间格式。请重新输入"); goto REDO; } // 这个日期是上次处理完成的那一天的后一天,也就是说下次处理,从这天开始即可 Program.MainForm.AppInfo.SetString(GetReportSection(), "daily_report_end_date", strLastDate); SetDailyReportButtonState(); return; #if NO ERROR1: MessageBox.Show(this, strError); #endif } // 根据最大尺寸,一次取得一部分文件名 // return: // -1 出错 // 其它 part_filenames 中包含的文字的总尺寸 long GetPartFileNames(ref List<string> filenames, long lMaxSize, out List<string> part_filenames, out string strError) { strError = ""; part_filenames = new List<string>(); long lTotalSize = 0; for (int i = 0; i < filenames.Count; i++) { string strFileName = filenames[i]; FileInfo fi = new FileInfo(strFileName); if (lTotalSize + fi.Length > lMaxSize && part_filenames.Count > 0) return lTotalSize; lTotalSize += fi.Length; part_filenames.Add(strFileName); filenames.RemoveAt(0); i--; } return lTotalSize; } // dp2Library 协议上传报表 void UploadReportByDp2library() { string strError = ""; int nRet = 0; #if SN #if REPORT_SN nRet = Program.MainForm.VerifySerialCode("report", false, out strError); if (nRet == -1) { strError = "上传报表功能尚未被许可"; goto ERROR1; } #endif #endif string strReportDir = Path.Combine(GetBaseDirectory(), "reports"); string strZipFileName = Path.Combine(GetBaseDirectory(), "reports.zip"); string strServerFileName = "!upload/reports/reports.zip"; DirectoryInfo di = new DirectoryInfo(strReportDir); if (di.Exists == false) { strError = "报表尚未创建,无法上传"; goto ERROR1; } List<string> filenames = null; long lZipFileLength = 0; long lUnzipFileLength = 0; long lUploadedFiles = 0; EnableControls(false); this.ChannelDoEvents = !this.InvokeRequired; stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在上传报表 ..."); stop.BeginLoop(); try { if (stop != null) stop.SetMessage("正在搜集文件名 ..."); if (this.InvokeRequired == false) Application.DoEvents(); // 获得全部文件名 filenames = GetFileNames(strReportDir, FileAttributes.Archive); if (filenames.Count == 0) { strError = "没有发现需要上传的文件"; goto NOT_FOUND; } long lTotalFiles = filenames.Count; // 分批进行上传 for (; ; ) { if (this.InvokeRequired == false) Application.DoEvents(); // 出让界面控制权 if (stop != null && stop.State != 0) { strError = "用户中断"; goto ERROR1; } if (filenames.Count == 0) break; List<string> part_filenames = null; // 取得一部分文件名 // 根据最大尺寸,一次取得一部分文件名 // return: // -1 出错 // 其它 part_filenames 中包含的文字的总尺寸 long lRet = GetPartFileNames(ref filenames, 5 * 1024 * 1024, out part_filenames, out strError); if (lRet == -1) goto ERROR1; lUnzipFileLength += lRet; if (part_filenames.Count == 0) break; // return: // -1 出错 // 0 没有发现需要上传的文件 // 1 成功压缩创建了 .zip 文件 nRet = CompressReport( stop, strReportDir, strZipFileName, Encoding.UTF8, part_filenames, // out filenames, out strError); if (nRet == -1) goto ERROR1; if (nRet == 0) { Debug.Assert(false, ""); strError = "没有发现需要上传的文件"; goto ERROR1; } FileInfo fi = new FileInfo(strZipFileName); lZipFileLength += fi.Length; stop.SetProgressRange(0, lTotalFiles); stop.SetProgressValue(lUploadedFiles); // return: // -1 出错 // 0 上传文件成功 nRet = UploadFile( this.stop, this.Channel, strZipFileName, strServerFileName, "extractzip", null, true, out strError); if (nRet == -1) goto ERROR1; bool bDelete = this.DeleteReportFileAfterUpload; foreach (string filename in part_filenames) { if (bDelete == true && IsRmlFileName(filename)) { try { File.Delete(filename); } catch { } } else File.SetAttributes(filename, FileAttributes.Normal); } lUploadedFiles += part_filenames.Count; stop.SetProgressValue(lUploadedFiles); } } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); stop.HideProgress(); EnableControls(true); } // SetUploadButtonState(); BeginUpdateUploadButtonText(); this.Invoke((Action)(() => { Program.MainForm.StatusBarMessage = "完成上传 " + lUploadedFiles.ToString() + " 个文件, 总尺寸" + lUnzipFileLength.ToString() + ",压缩后尺寸 " + lZipFileLength.ToString(); if (this.DeleteReportFileAfterUpload == true && lUploadedFiles > 0) Program.MainForm.StatusBarMessage += "。文件上传后,本地文件已经被删除"; })); return; NOT_FOUND: this.Invoke((Action)(() => { Program.MainForm.StatusBarMessage = strError; })); return; ERROR1: BeginUpdateUploadButtonText(); this.Invoke((Action)(() => { MessageBox.Show(this, strError); })); } static bool IsRmlFileName(string strFileName) { if (string.Compare(Path.GetExtension(strFileName), ".rml", true) == 0) return true; return false; } void UploadReportByFtp() { string strError = ""; int nUploadCount = 0; int nRet = 0; #if SN #if REPORT_SN nRet = Program.MainForm.VerifySerialCode("report", false, out strError); if (nRet == -1) { strError = "上传报表功能尚未被许可"; goto ERROR1; } #endif #endif FtpUploadDialog dlg = new FtpUploadDialog(); MainForm.SetControlFont(dlg, this.Font, false); // dlg.MainForm = Program.MainForm; Program.MainForm.AppInfo.LinkFormState(dlg, "FtpUploadDialog_state"); dlg.UiState = Program.MainForm.AppInfo.GetString(GetReportSection(), "FtpUploadDialog_ui_state", ""); dlg.ShowDialog(this); Program.MainForm.AppInfo.SetString(GetReportSection(), "FtpUploadDialog_ui_state", dlg.UiState); Program.MainForm.AppInfo.UnlinkFormState(dlg); if (dlg.DialogResult == System.Windows.Forms.DialogResult.Cancel) return; if (stop != null) stop.SetMessage("正在搜集文件名 ..."); if (this.InvokeRequired == false) Application.DoEvents(); string strReportDir = Path.Combine(GetBaseDirectory(), "reports"); List<string> filenames = null; bool bDelete = this.DeleteReportFileAfterUpload; if (this.InvokeRequired == false) Application.DoEvents(); filenames = GetFileNames(strReportDir, FileAttributes.Archive); if (filenames.Count == 0) { strError = "没有发现要上传的报表文件"; goto ERROR1; } EnableControls(false); stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在上传报表 ..."); stop.BeginLoop(); try { Hashtable dir_table = new Hashtable(); stop.SetProgressRange(0, filenames.Count); int i = 0; foreach (string filename in filenames) { if (this.InvokeRequired == false) Application.DoEvents(); // 出让界面控制权 if (stop != null && stop.State != 0) { strError = "用户中断"; goto ERROR1; } // string strPath = Path.GetDirectoryName(filename.Substring(strReportDir.Length + 1)); string strPath = filename.Substring(strReportDir.Length + 1); stop.SetMessage("正在上传 " + filename); // 上传文件 // 自动创建所需的目录 // 不会抛出异常 nRet = FtpUploadDialog.SafeUploadFile(ref dir_table, filename, dlg.FtpServerUrl, (string.IsNullOrEmpty(dlg.TargetDir) == false ? dlg.TargetDir + "/" : "") + strPath, dlg.UserName, dlg.Password, out strError); if (nRet == -1) goto ERROR1; if (bDelete == true && IsRmlFileName(filename)) { try { File.Delete(filename); } catch { } } else File.SetAttributes(filename, FileAttributes.Normal); i++; stop.SetProgressValue(i); nUploadCount++; } } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); stop.HideProgress(); EnableControls(true); } if (nUploadCount > 0) { // SetUploadButtonState(); BeginUpdateUploadButtonText(); } Program.MainForm.StatusBarMessage = "完成上传 " + nUploadCount.ToString() + " 个文件"; if (this.DeleteReportFileAfterUpload == true && nUploadCount > 0) Program.MainForm.StatusBarMessage += "。文件上传后,本地文件已经被删除"; return; ERROR1: if (nUploadCount > 0) { // SetUploadButtonState(); BeginUpdateUploadButtonText(); } this.Invoke((Action)(() => { MessageBox.Show(this, strError); })); } // 上传报表 private void button_start_uploadReport_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(this.comboBox_start_uploadMethod.Text) == true || this.comboBox_start_uploadMethod.GetText() == "dp2Library") UploadReportByDp2library(); else if (this.comboBox_start_uploadMethod.GetText() == "FTP") UploadReportByFtp(); else { this.Invoke((Action)(() => { MessageBox.Show(this, "未知的上传方式 '" + this.comboBox_start_uploadMethod.GetText() + "'"); })); } } // 上传文件到到 dp2lbrary 服务器 // parameters: // timestamp 时间戳。如果为 null,函数会自动根据文件信息得到一个时间戳 // bRetryOverwiteExisting 是否自动在时间戳不一致的情况下覆盖已经存在的服务器文件。== true,表示当发现时间戳不一致的时候,自动用返回的时间戳重试覆盖 // return: // -1 出错 // 0 上传文件成功 static int UploadFile( Stop stop, LibraryChannel channel, string strClientFilePath, string strServerFilePath, string strStyle, byte[] timestamp, bool bRetryOverwiteExisting, // string strMessagePrefix, out string strError) { strError = ""; string strResPath = strServerFilePath; #if NO string strMime = API.MimeTypeFrom(ResObjectDlg.ReadFirst256Bytes(strClientFilePath), ""); #endif string strMime = PathUtil.MimeTypeFrom(strClientFilePath); // 检测文件尺寸 FileInfo fi = new FileInfo(strClientFilePath); if (fi.Exists == false) { strError = "文件 '" + strClientFilePath + "' 不存在..."; return -1; } string[] ranges = null; if (fi.Length == 0) { // 空文件 ranges = new string[1]; ranges[0] = ""; } else { string strRange = ""; strRange = "0-" + Convert.ToString(fi.Length - 1); // 按照100K作为一个chunk // TODO: 实现滑动窗口,根据速率来决定chunk尺寸 ranges = RangeList.ChunkRange(strRange, channel.UploadResChunkSize // 500 * 1024 ); } if (timestamp == null) timestamp = FileUtil.GetFileTimestamp(strClientFilePath); byte[] output_timestamp = null; // REDOWHOLESAVE: string strWarning = ""; TimeSpan old_timeout = channel.Timeout; try { for (int j = 0; j < ranges.Length; j++) { if (Program.MainForm.InvokeRequired == false) Application.DoEvents(); // 出让界面控制权 if (stop != null && stop.State != 0) { strError = "用户中断"; goto ERROR1; } string strWaiting = ""; if (j == ranges.Length - 1) { strWaiting = " 请耐心等待..."; channel.Timeout = new TimeSpan(0, 40, 0); // 40 分钟 } string strPercent = ""; RangeList rl = new RangeList(ranges[j]); if (rl.Count >= 1) { double ratio = (double)((RangeItem)rl[0]).lStart / (double)fi.Length; strPercent = String.Format("{0,3:N}", ratio * (double)100) + "%"; } if (stop != null) stop.SetMessage( // strMessagePrefix + "正在上载 " + ranges[j] + "/" + Convert.ToString(fi.Length) + " " + strPercent + " " + strClientFilePath + strWarning + strWaiting); int nRedoCount = 0; REDO: long lRet = channel.SaveResObject( stop, strResPath, strClientFilePath, strClientFilePath, strMime, ranges[j], // j == ranges.Length - 1 ? true : false, // 最尾一次操作,提醒底层注意设置特殊的WebService API超时时间 timestamp, strStyle, out output_timestamp, out strError); timestamp = output_timestamp; strWarning = ""; if (lRet == -1) { // 如果是第一个 chunk,自动用返回的时间戳重试一次覆盖 if (bRetryOverwiteExisting == true && j == 0 && channel.ErrorCode == DigitalPlatform.LibraryClient.localhost.ErrorCode.TimestampMismatch && nRedoCount == 0) { nRedoCount++; goto REDO; } goto ERROR1; } } } finally { channel.Timeout = old_timeout; } return 0; ERROR1: return -1; } // 把报表子目录中的文件压缩到一个 .zip 文件中 // parameters: // strReportDir 最后不要带有符号 '/' // return: // -1 出错 // 0 没有发现需要上传的文件 // 1 成功压缩创建了 .zip 文件 static int CompressReport( Stop stop, string strReportDir, string strZipFileName, Encoding encoding, List<string> filenames, // out List<string> filenames, out string strError) { strError = ""; #if NO if (stop != null) stop.SetMessage("正在搜集文件名 ..."); if (this.InvokeRequired == false) Application.DoEvents(); filenames = GetFileNames(strReportDir, FileAttributes.Archive); #endif if (filenames.Count == 0) return 0; bool bRangeSetted = false; using (ZipFile zip = new ZipFile(encoding)) { // http://stackoverflow.com/questions/15337186/dotnetzip-badreadexception-on-extract // https://dotnetzip.codeplex.com/workitem/14087 // uncommenting the following line can be used as a work-around zip.ParallelDeflateThreshold = -1; foreach (string filename in filenames) { if (Program.MainForm.InvokeRequired == false) Application.DoEvents(); if (stop != null && stop.State != 0) { strError = "用户中断"; return -1; } string strShortFileName = filename.Substring(strReportDir.Length + 1); if (stop != null) stop.SetMessage("正在压缩 " + strShortFileName); string directoryPathInArchive = Path.GetDirectoryName(strShortFileName); zip.AddFile(filename, directoryPathInArchive); } if (stop != null) stop.SetMessage("正在写入压缩文件 ..."); if (Program.MainForm.InvokeRequired == false) Application.DoEvents(); zip.SaveProgress += (s, e) => { if (Program.MainForm.InvokeRequired == false) Application.DoEvents(); if (stop != null && stop.State != 0) { e.Cancel = true; return; } if (e.EventType == ZipProgressEventType.Saving_AfterWriteEntry) { if (bRangeSetted == false) { stop.SetProgressRange(0, e.EntriesTotal); bRangeSetted = true; } stop.SetProgressValue(e.EntriesSaved); } }; zip.UseZip64WhenSaving = Zip64Option.AsNecessary; zip.Save(strZipFileName); stop.HideProgress(); if (stop != null && stop.State != 0) { strError = "用户中断"; return -1; } } return 1; } // TODO: 可以尝试用通用版本的 GetFileNames() 加上回调函数定制出本函数 // 获得一个目录下的全部文件名。包括子目录中的 static List<string> GetFileNames(string strDataDir, FileAttributes attr) { // Application.DoEvents(); DirectoryInfo di = new DirectoryInfo(strDataDir); List<string> result = new List<string>(); FileInfo[] fis = di.GetFiles(); foreach (FileInfo fi in fis) { if ((fi.Attributes & attr) == attr) { string strExtention = Path.GetExtension(fi.Name).ToLower(); if (strExtention == ".xml" || strExtention == ".rml") result.Add(fi.FullName); } } // 处理下级目录,递归 DirectoryInfo[] dis = di.GetDirectories(); foreach (DirectoryInfo subdir in dis) { result.AddRange(GetFileNames(subdir.FullName, attr)); } return result; } private void timer_qu_Tick(object sender, EventArgs e) { this.listView_query_results.ForceUpdate(); } private void listView_query_results_SelectedIndexChanged(object sender, EventArgs e) { if (this.listView_query_results.SelectedIndices.Count == 0) Program.MainForm.StatusBarMessage = ""; else Program.MainForm.StatusBarMessage = this.listView_query_results.SelectedIndices[0].ToString(); } /// <summary> /// 获取或设置控件尺寸状态 /// </summary> public string UiState { get { List<object> controls = new List<object>(); controls.Add(this.tabControl1); controls.Add(this.listView_libraryConfig); controls.Add(this.splitContainer_query); controls.Add(this.comboBox_start_uploadMethod); return GuiState.GetUiState(controls); } set { List<object> controls = new List<object>(); controls.Add(this.tabControl1); controls.Add(this.listView_libraryConfig); controls.Add(this.splitContainer_query); controls.Add(this.comboBox_start_uploadMethod); GuiState.SetUiState(controls, value); } } // TODO: 可以尝试用通用版本的 GetFileNames() 加上回调函数定制出本函数 // 获得一个目录下的全部 .rml 文件名。包括子目录中的 static List<string> GetRmlFileNames(string strDataDir) { if (Program.MainForm.InvokeRequired == false) Application.DoEvents(); DirectoryInfo di = new DirectoryInfo(strDataDir); List<string> result = new List<string>(); FileInfo[] fis = di.GetFiles(); foreach (FileInfo fi in fis) { string strExtention = Path.GetExtension(fi.Name).ToLower(); if (strExtention == ".rml") result.Add(fi.FullName); } // 处理下级目录,递归 DirectoryInfo[] dis = di.GetDirectories(); foreach (DirectoryInfo subdir in dis) { result.AddRange(GetRmlFileNames(subdir.FullName)); } return result; } private void toolStripButton_convertFormat_Click(object sender, EventArgs e) { string strError = ""; int nRet = 0; ConvertReportFormatDialog dlg = new ConvertReportFormatDialog(); MainForm.SetControlFont(dlg, this.Font, false); // dlg.MainForm = Program.MainForm; Program.MainForm.AppInfo.LinkFormState(dlg, "ConvertReportFormatDialog_state"); dlg.UiState = Program.MainForm.AppInfo.GetString(GetReportSection(), "ConvertReportFormatDialog_ui_state", ""); dlg.ShowDialog(this); Program.MainForm.AppInfo.SetString(GetReportSection(), "ConvertReportFormatDialog_ui_state", dlg.UiState); Program.MainForm.AppInfo.UnlinkFormState(dlg); if (dlg.DialogResult == System.Windows.Forms.DialogResult.Cancel) return; string strTemplate = ""; if (dlg.ToHtml == true) { nRet = LoadHtmlTemplate(null, // nodeLibrary, out strTemplate, out strError); if (nRet == -1) goto ERROR1; } int nCount = 0; EnableControls(false); stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在转换格式 ..."); stop.BeginLoop(); try { if (stop != null) stop.SetMessage("正在搜集文件名 ..."); if (this.InvokeRequired == false) Application.DoEvents(); List<string> filenames = GetRmlFileNames(dlg.ReportDirectory); if (filenames.Count == 0) { strError = "所指定的目录 '" + dlg.ReportDirectory + "' 中没有任何 .tml 文件"; goto ERROR1; } if (stop != null) stop.SetProgressRange(0, filenames.Count); int i = 0; foreach (string strFileName in filenames) { if (this.InvokeRequired == false) Application.DoEvents(); // 出让界面控制权 if (stop != null && stop.State != 0) { strError = "用户中断"; goto ERROR1; } if (stop != null) stop.SetMessage("正在转换文件 " + strFileName); // 创建 .html 文件 if (dlg.ToHtml == true) { string strHtmlFileName = Path.Combine(Path.GetDirectoryName(strFileName), Path.GetFileNameWithoutExtension(strFileName) + ".html"); nRet = Report.RmlToHtml(strFileName, strHtmlFileName, strTemplate, out strError); if (nRet == -1) goto ERROR1; RemoveArchiveAttribute(strHtmlFileName); nCount++; } // 创建 Excel 文件 if (dlg.ToExcel == true) { string strExcelFileName = Path.Combine(Path.GetDirectoryName(strFileName), Path.GetFileNameWithoutExtension(strFileName) + ".xlsx"); nRet = Report.RmlToExcel(strFileName, strExcelFileName, out strError); if (nRet == -1) goto ERROR1; RemoveArchiveAttribute(strExcelFileName); nCount++; } if (stop != null) stop.SetProgressValue(++i); } } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); stop.HideProgress(); EnableControls(true); } this.Invoke((Action)(() => { MessageBox.Show(this, "成功转换文件 " + nCount.ToString() + " 个"); })); return; ERROR1: this.Invoke((Action)(() => { MessageBox.Show(this, strError); })); } FileCounting _counting = null; // 启动更新 上载报表 按钮文字的线程 void BeginUpdateUploadButtonText() { if (this._counting == null) { this._counting = new FileCounting(); this._counting.ReportForm = this; this._counting.Directory = Path.Combine(GetBaseDirectory(), "reports"); } this._counting.BeginThread(); } void StopUpdateUploadButtonText() { if (this._counting != null) this._counting.StopThread(true); } private void tabPage_option_Enter(object sender, EventArgs e) { // Debug.WriteLine("Enter page"); this.checkBox_option_deleteReportFileAfterUpload.Checked = Program.MainForm.AppInfo.GetBoolean(GetReportSection(), "deleteReportFileAfterUpload", true); } private void tabPage_option_Leave(object sender, EventArgs e) { // Debug.WriteLine("Leave page"); Program.MainForm.AppInfo.SetBoolean(GetReportSection(), "deleteReportFileAfterUpload", this.checkBox_option_deleteReportFileAfterUpload.Checked); } /// <summary> /// 是否要在上载成功后自动删除本地报表文件 /// </summary> public bool DeleteReportFileAfterUpload { get { return Program.MainForm.AppInfo.GetBoolean(GetReportSection(), "deleteReportFileAfterUpload", true); } } private void listView_query_results_MouseUp(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Right) return; ContextMenu contextMenu = new ContextMenu(); MenuItem menuItem = null; menuItem = new MenuItem("全选(&A)"); menuItem.Click += new System.EventHandler(this.menu_queryResult_selectAll_Click); contextMenu.MenuItems.Add(menuItem); // --- menuItem = new MenuItem("-"); contextMenu.MenuItems.Add(menuItem); menuItem = new MenuItem("复制 [" + this.listView_query_results.SelectedItems.Count.ToString() + "] (&C)"); menuItem.Click += new System.EventHandler(this.menu_queryResult_copyToClipboard_Click); if (this.listView_query_results.SelectedIndices.Count == 0) menuItem.Enabled = false; contextMenu.MenuItems.Add(menuItem); // --- menuItem = new MenuItem("-"); contextMenu.MenuItems.Add(menuItem); menuItem = new MenuItem("保存到 Excel 文件 [" + this.listView_query_results.SelectedItems.Count.ToString() + "] (&S) ..."); menuItem.Click += new System.EventHandler(this.menu_queryResult_saveToExcel_Click); if (this.listView_query_results.SelectedItems.Count == 0) menuItem.Enabled = false; contextMenu.MenuItems.Add(menuItem); contextMenu.Show(this.listView_query_results, new Point(e.X, e.Y)); } void menu_queryResult_selectAll_Click(object sender, EventArgs e) { ListViewUtil.SelectAllLines(this.listView_query_results); } string _exportExcelFileName = ""; void menu_queryResult_saveToExcel_Click(object sender, EventArgs e) { string strError = ""; if (this.listView_query_results.SelectedItems.Count == 0) { strError = "尚未选择要保存的行"; goto ERROR1; } // 询问文件名 SaveFileDialog dlg = new SaveFileDialog(); dlg.Title = "请指定要保存的 Excel 文件名"; dlg.CreatePrompt = false; dlg.OverwritePrompt = true; dlg.FileName = _exportExcelFileName; // dlg.InitialDirectory = Environment.CurrentDirectory; dlg.Filter = "Excel 文件 (*.xlsx)|*.xlsx|All files (*.*)|*.*"; dlg.RestoreDirectory = true; if (dlg.ShowDialog() != DialogResult.OK) return; _exportExcelFileName = dlg.FileName; this.EnableControls(false); try { ExcelDocument doc = ExcelDocument.Create(dlg.FileName); try { doc.NewSheet("Sheet1"); int nColIndex = 0; int _lineIndex = 0; // 姓名 List<CellData> cells = new List<CellData>(); foreach (ColumnHeader column in this.listView_query_results.Columns) { cells.Add(new CellData(nColIndex++, column.Text)); } doc.WriteExcelLine(_lineIndex, cells, WriteExcelLineStyle.None); _lineIndex++; foreach (ListViewItem item in this.listView_query_results.SelectedItems) { cells = new List<CellData>(); nColIndex = 0; foreach (ListViewItem.ListViewSubItem subitem in item.SubItems) { cells.Add(new CellData(nColIndex++, subitem.Text)); } doc.WriteExcelLine(_lineIndex, cells, WriteExcelLineStyle.AutoString); _lineIndex++; } } finally { doc.SaveWorksheet(); doc.Close(); } } finally { this.EnableControls(true); } Program.MainForm.StatusBarMessage = "导出成功。"; return; ERROR1: this.Invoke((Action)(() => { MessageBox.Show(this, strError); })); } void menu_queryResult_copyToClipboard_Click(object sender, EventArgs e) { Global.CopyLinesToClipboard(this, this.listView_query_results, false); } private void toolStripButton_openReportFolder_Click(object sender, EventArgs e) { try { System.Diagnostics.Process.Start(GetReportDir()); } catch (Exception ex) { MessageBox.Show(this, ExceptionUtil.GetAutoText(ex)); } } } class FileCounting : ThreadBase { public string Directory = ""; public ReportForm ReportForm = null; internal ReaderWriterLock m_lock = new ReaderWriterLock(); internal static int m_nLockTimeout = 5000; // 5000=5秒 // 工作线程每一轮循环的实质性工作 public override void Worker() { this.m_lock.AcquireWriterLock(m_nLockTimeout); try { if (this.Stopped == true) return; this.ReportForm.SetUploadButtonText("上传报表 ?", "false"); string strReportDir = this.Directory; DirectoryInfo di = new DirectoryInfo(strReportDir); if (di.Exists == false) { // 报表目录不存在 this.ReportForm.SetUploadButtonText("上传报表", "false"); return; } long lCount = CountFiles(this.Directory, FileAttributes.Archive); this.ReportForm.SetUploadButtonText("上传报表 (" + lCount.ToString() + ")", "true"); this.Stopped = true; // 只作一轮就停止 } finally { this.m_lock.ReleaseWriterLock(); } } // 获得一个目录下的全部文件数目。包括子目录中的 long CountFiles(string strDataDir, FileAttributes attr) { DirectoryInfo di = new DirectoryInfo(strDataDir); long lCount = 0; List<string> result = new List<string>(); FileInfo[] fis = di.GetFiles(); foreach (FileInfo fi in fis) { if (this.Stopped == true) return lCount; if ((fi.Attributes & attr) == attr) { // Thread.Sleep(1); 测试用 string strExtention = Path.GetExtension(fi.Name).ToLower(); if (strExtention == ".xml" || strExtention == ".rml") lCount++; } } // 处理下级目录,递归 DirectoryInfo[] dis = di.GetDirectories(); foreach (DirectoryInfo subdir in dis) { if (this.Stopped == true) return lCount; lCount += CountFiles(subdir.FullName, attr); } return lCount; } } class OneClassType { /// <summary> /// 分类号 type。例如 clc /// </summary> public string ClassType = ""; /// <summary> /// 类名细目。不允许元素为空字符串。如果 .Count == 0 ,表示不使用细目,统一截取第一个字符作为细目 /// </summary> public List<string> Filters = new List<string>(); // 根据名字表创建分类号分级结构 /* 名字表形态如下 * clc * A * B * stt * nhb * */ public static int BuildClassTypes(string strNameTable, out List<OneClassType> results, out string strError) { strError = ""; results = new List<OneClassType>(); List<string> lines = StringUtil.SplitList(strNameTable); OneClassType current = null; foreach (string line in lines) { if (string.IsNullOrEmpty(line) == true) continue; string strLine = line.TrimEnd(); if (string.IsNullOrEmpty(strLine) == true) continue; if (strLine[0] != ' ') { current = new OneClassType(); results.Add(current); current.ClassType = strLine.Trim(); } else { if (current == null) { strError = "第一行的第一字符不能为空格"; return -1; } string strText = strLine.Substring(1).Trim(); current.Filters.Add(strText); } } // 将 Filters 数组排序,大的在前 // 这样让 I1 比 I 先匹配上 foreach (OneClassType type in results) { type.Filters.Sort( delegate (string s1, string s2) { return -1 * string.Compare(s1, s2); }); } return 0; } public static int IndexOf(List<OneClassType> types, string strTypeName) { int i = 0; foreach (OneClassType type in types) { if (type.ClassType == strTypeName) return i; i++; } return -1; } } }
36.861857
377
0.444201
[ "Apache-2.0" ]
jasonliaocn/dp2
dp2Circulation/Statis/ReportForm.cs
551,528
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Playables; using ScenarioController; /// <summary> /// Scenarioが表示されるかテストする /// </summary> public class ScenarioTest : MonoBehaviour { public ScenarioInput input; void Update() { if (Input.GetKeyDown(KeyCode.X)) input.PlayScenario(); if (Input.GetKeyDown(KeyCode.Z)) input.scenarioDisplayBase.Next(); if (Input.GetKeyDown(KeyCode.C)) input.scenarioDisplayBase.ForceStop(); } }
24.5
79
0.723562
[ "MIT" ]
NidoKota/UnityScenarioController
Assets/Scripts/ScenarioTest.cs
565
C#
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Ordering.Application.Contracts.Infrastructure; using Ordering.Application.Models; using SendGrid; using SendGrid.Helpers.Mail; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ordering.Infrastructure.Mail { public class EmailService : IEmailService { public EmailSettings _emailSettings { get; } public ILogger<EmailService> _logger { get; } public EmailService(IOptions<EmailSettings> emailSettings, ILogger<EmailService> logger) { _emailSettings = emailSettings.Value; _logger = logger; } public async Task<bool> SendEmail(Email email) { var client = new SendGridClient(_emailSettings.ApiKey); var subject = email.Subject; var to = new EmailAddress(email.To); var emailBody = email.Body; var from = new EmailAddress { Email = _emailSettings.FromAddress, Name = _emailSettings.FromName }; var sendGridMessage = MailHelper.CreateSingleEmail(from, to, subject, emailBody, emailBody); var response = await client.SendEmailAsync(sendGridMessage); _logger.LogInformation("Email sent"); if (response.StatusCode == System.Net.HttpStatusCode.Accepted || response.StatusCode == System.Net.HttpStatusCode.OK) { return true; } _logger.LogError("Email sending failed."); return false; } } }
28.913793
129
0.639237
[ "MIT" ]
Azilen/gRPC-API-Performance-Improvement
src/Services/Ordering/Ordering.Infrastructure/Mail/EmailService.cs
1,679
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.AzureNextGen.Network.V20190701.Inputs { /// <summary> /// Defines contents of a web application rule. /// </summary> public sealed class WebApplicationFirewallCustomRuleArgs : Pulumi.ResourceArgs { /// <summary> /// Type of Actions. /// </summary> [Input("action", required: true)] public Input<string> Action { get; set; } = null!; [Input("matchConditions", required: true)] private InputList<Inputs.MatchConditionArgs>? _matchConditions; /// <summary> /// List of match conditions. /// </summary> public InputList<Inputs.MatchConditionArgs> MatchConditions { get => _matchConditions ?? (_matchConditions = new InputList<Inputs.MatchConditionArgs>()); set => _matchConditions = value; } /// <summary> /// The name of the resource that is unique within a policy. This name can be used to access the resource. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// Describes priority of the rule. Rules with a lower value will be evaluated before rules with a higher value. /// </summary> [Input("priority", required: true)] public Input<int> Priority { get; set; } = null!; /// <summary> /// Describes type of rule. /// </summary> [Input("ruleType", required: true)] public Input<string> RuleType { get; set; } = null!; public WebApplicationFirewallCustomRuleArgs() { } } }
32.677966
120
0.60944
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Network/V20190701/Inputs/WebApplicationFirewallCustomRuleArgs.cs
1,928
C#
using System.Globalization; using System.Reflection; using ClosedXML.Excel; namespace Netcool.Excel; public class ExcelImporter<T> where T : class, new() { private IList<ExcelColumnMetadata> _columns; private string _sheetName; private XLWorkbook _workbook; private int _headerRowIndex; public ExcelImporter() { var objType = typeof(T); var columnMetadataList = new List<ExcelColumnMetadata>(); var properties = GetPublicProperties(objType); if (properties.Count == 0) return; foreach (var propertyInfo in properties) { columnMetadataList.Add(ExcelColumnMetadata.ForPropertyInfo(propertyInfo)); } _columns = columnMetadataList.Where(t => !t.IgnoreColumn).ToList(); } public ExcelImporter<T> FromFile(string path) { if (string.IsNullOrEmpty(path)) throw new ArgumentException("File path cannot be null."); _workbook = new XLWorkbook(path, XLEventTracking.Disabled); return this; } public ExcelImporter<T> FromFile(Stream stream) { _workbook = new XLWorkbook(stream, XLEventTracking.Disabled); return this; } /// <summary> /// Specify the sheet name workbook, if null then reading the first worksheet. /// </summary> /// <param name="sheetName"></param> public ExcelImporter<T> WithSheetName(string sheetName) { _sheetName = sheetName; return this; } /// <summary> /// Specify the header row index, starts from 1, if null then reading the first row. /// </summary> /// <param name="index"></param> public ExcelImporter<T> WithHeaderRowIndex(int index = 1) { _headerRowIndex = index; return this; } private List<PropertyInfo> GetPublicProperties(Type type) { return type.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList(); } public List<T> Import() { if (_workbook == null) throw new ApplicationException("Workbook did not loaded."); IXLWorksheet ws; if (string.IsNullOrEmpty(_sheetName)) { ws = _workbook.Worksheet(1); if (ws == null) throw new ArgumentException("Cannot read the worksheet at position 1."); } else { ws = _workbook.Worksheet(_sheetName); if (ws == null) throw new ArgumentException($"Cannot read the worksheet with name {_sheetName}."); } if (_headerRowIndex <= 0) _headerRowIndex = 1; var headerRow = ws.Row(_headerRowIndex); if (headerRow == null) throw new ArgumentException($"Cannot read the header row with index {_headerRowIndex}."); var headerCells = headerRow.CellsUsed(); if (headerCells == null || !headerCells.Any()) throw new ArgumentException($"Cannot read header cells with row index {_headerRowIndex}."); var columnDict = _columns.ToDictionary(t => t.HeaderName, t => t); foreach (var headerCell in headerCells) { var columnIndex = headerCell.WorksheetColumn().ColumnNumber(); var headName = headerCell.GetString(); if (columnDict.TryGetValue(headName, out var metadata)) { metadata.Index = columnIndex; } } var dataRows = ws.RowsUsed(t => t.RowNumber() != headerRow.RowNumber()); if (dataRows == null || !dataRows.Any()) return null; var list = new List<T>(); foreach (var row in dataRows) { var t = new T(); foreach (var metadata in _columns) { if (metadata.Index <= 0) continue; var cellStr = row.Cell(metadata.Index).GetString(); var value = MapPropertyValue(t, metadata.PropertyInfo, cellStr); if (value != null) metadata.PropertyInfo.SetValue(t, value); } list.Add(t); } _workbook.Dispose(); return list; } private object MapPropertyValue(T v, PropertyInfo pi, string cellString) { if (string.IsNullOrEmpty(cellString)) return null; object newValue; if (pi.PropertyType == typeof(Guid)) { newValue = Guid.Parse(cellString); } else if (pi.PropertyType == typeof(DateTime)) { if (DateTime.TryParse(cellString, CultureInfo.InvariantCulture, DateTimeStyles.None, out var tempValue)) newValue = tempValue; else if (DateTime.TryParseExact(cellString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out var tempValue2)) newValue = tempValue2; else throw new InvalidCastException($"{cellString} can't cast to datetime"); } else if (pi.PropertyType == typeof(bool)) { if (cellString == "1") newValue = true; else if (cellString == "0") newValue = false; else newValue = bool.Parse(cellString); } else if (pi.PropertyType == typeof(string)) { newValue = cellString; } else if (pi.PropertyType.IsEnum) { newValue = Enum.Parse(pi.PropertyType, cellString, true); } else { newValue = Convert.ChangeType(cellString, pi.PropertyType); } pi.SetValue(v, newValue); return newValue; } }
33.161677
120
0.591008
[ "Apache-2.0" ]
NeilQ/Netcool
src/extensions/Netcool.Excel/TypedExcelImporter.cs
5,540
C#
namespace ReflectionAnalyzers.Tests.REFL028CastReturnValueToCorrectTypeTests { using Gu.Roslyn.Asserts; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using NUnit.Framework; public class ValidCode { public class ActivatorCreateInstance { private static readonly DiagnosticAnalyzer Analyzer = new ActivatorAnalyzer(); private static readonly DiagnosticDescriptor Descriptor = REFL028CastReturnValueToCorrectType.Descriptor; [TestCase("(C)")] [TestCase("(IDisposable)")] public void WhenCasting(string cast) { var code = @" namespace RoslynSandbox { using System; public sealed class C : IDisposable { public C() { var foo = (C)Activator.CreateInstance(typeof(C)); } public void Dispose() { } } }".AssertReplace("(C)", cast); AnalyzerAssert.Valid(Analyzer, Descriptor, code); } [Test] public void WhenUnknown() { var code = @" namespace RoslynSandbox { using System; public class C { public static object Bar(Type type) => Activator.CreateInstance(type, ""foo""); } }"; AnalyzerAssert.Valid(Analyzer, Descriptor, code); } [Test] public void WhenUnconstrainedGeneric() { var code = @" namespace RoslynSandbox { using System; public class C { public static object Bar<T>() => (T)Activator.CreateInstance(typeof(T), ""foo""); } }"; AnalyzerAssert.Valid(Analyzer, Descriptor, code); } } } }
23.626667
117
0.566591
[ "MIT" ]
jaggedSpire/ReflectionAnalyzers
ReflectionAnalyzers.Tests/REFL028CastReturnValueToCorrectTypeTests/ValidCode.ActivatorCreateInstance.cs
1,772
C#
using System.Collections.Generic; namespace RedFolder.ViewModels { public class RecentProject { public string Title { get; set; } public List<string> Description { get; set; } public Diciplines Diciplines { get; set; } public List<string> Technologies { get; set; } } }
24.307692
54
0.642405
[ "MIT" ]
Red-Folder/red-folder.com
src/Red-Folder.com/ViewModels/RecentProject.cs
318
C#
using Cosmos.Conversions.Common; using Cosmos.Reflection; using NodaTime; namespace Cosmos.Date; /// <summary> /// DateInfo <br /> /// 日期信息 /// </summary> public partial class DateInfo { // ReSharper disable once InconsistentNaming private DateTime _internalDateTime { get; set; } internal DateInfo() { } /// <summary> /// Create a new instance of <see cref="DateInfo"/>.<br /> /// 创建一个新的 <see cref="DateInfo"/> 实例。 /// </summary> /// <param name="dt"></param> public DateInfo(DateTime dt) { _internalDateTime = dt.Date; } /// <summary> /// Create a new instance of <see cref="DateInfo"/>.<br /> /// 创建一个新的 <see cref="DateInfo"/> 实例。 /// </summary> /// <param name="year"></param> /// <param name="month"></param> /// <param name="day"></param> public DateInfo(int year, int month, int day) { _internalDateTime = new DateTime(year, month, day); } static DateInfo() { // to register DateInfo ConvertHandler and Checker into CustomConvertManager CustomConvertManager.RegisterOrOverride( TypeClass.StringClazz, typeof(DateInfo), StringConvBeHandler, StringConvToHandler); } /// <summary> /// Year<br /> /// 年 /// </summary> public virtual int Year { get => _internalDateTime.Year; set => _internalDateTime = _internalDateTime.SetYear(value); } /// <summary> /// Month<br /> /// 月份 /// </summary> public virtual int Month { get => _internalDateTime.Month; set => _internalDateTime = _internalDateTime.SetMonth(DateChecker.CheckMonth(value)); } /// <summary> /// Day<br /> /// 日 /// </summary> public virtual int Day { get => _internalDateTime.Day; set => _internalDateTime = _internalDateTime.SetDay(value); } /// <summary> /// Ticks<br /> /// 获取表示此实例的日期的计时周期数。 /// </summary> public virtual long Ticks => _internalDateTime.Ticks; public static DateInfo Today => new(DateTime.Today); /// <summary> /// Convert to <see cref="DateTime"/><br /> /// 转换为 <see cref="DateTime"/> /// </summary> /// <returns></returns> public virtual DateTime ToDateTime() => _internalDateTime.Clone(); /// <summary> /// Convert to <see cref="DateOnly"/><br /> /// 转换为 <see cref="DateOnly"/> /// </summary> /// <returns></returns> public virtual DateOnly ToDateOnly() => DateOnly.FromDateTime(_internalDateTime); /// <summary> /// Convert to <see cref="LocalDate"/>. <br /> /// 转换为本地日期 /// </summary> /// <returns></returns> public LocalDate ToLocalDate() => LocalDate.FromDateTime(_internalDateTime); /// <summary> /// Convert to <see cref="LocalDateTime"/>. <br /> /// 转换为本地日期时间 /// </summary> /// <returns></returns> public LocalDateTime ToLocalDateTime() => LocalDateTime.FromDateTime(_internalDateTime); internal DateTime DateTimeRef => _internalDateTime; private static class DateChecker { public static int CheckMonth(int monthValue) { if (monthValue < 0 || monthValue > 12) throw new ArgumentOutOfRangeException(nameof(monthValue), monthValue, "Month should be from 1 to 12."); return monthValue; } } /// <summary> /// Add days<br /> /// 添加天数 /// </summary> /// <param name="days"></param> /// <returns></returns> public DateInfo AddDays(int days) { _internalDateTime += days.Days(); return this; } /// <summary> /// Add months<br /> /// 添加月份 /// </summary> /// <param name="months"></param> /// <returns></returns> public DateInfo AddMonths(int months) { _internalDateTime += months.Months(); return this; } /// <summary> /// Add years<br /> /// 添加年份 /// </summary> /// <param name="years"></param> /// <returns></returns> public DateInfo AddYears(int years) { _internalDateTime += years.Years(); return this; } /// <summary> /// Add duration<br /> /// 添加一段时间段 /// </summary> /// <param name="duration"></param> /// <returns></returns> public DateInfo AddDuration(Duration duration) { _internalDateTime = _internalDateTime.AddDuration(duration); return this; } /// <summary> /// Gets day of week <br /> /// 获取 DayOfWeek /// </summary> public DayOfWeek DayOfWeek => DateTimeRef.DayOfWeek; /// <summary> /// Convert <see cref="DateTime"/> to <see cref="DateInfo"/><br /> /// 将 <see cref="DateTime"/> 转换为 <see cref="DateInfo"/>。 /// </summary> /// <param name="di"></param> public static implicit operator DateTime(DateInfo di) { return di.ToDateTime(); } /// <summary> /// Convert <see cref="DateInfo"/> to <see cref="DateTime"/><br /> /// 将 <see cref="DateInfo"/> 转换为 <see cref="DateTime"/>。 /// </summary> /// <param name="dt"></param> public static implicit operator DateInfo(DateTime dt) { return new(dt); } /// <summary> /// Convert <see cref="DateOnly"/> to <see cref="DateInfo"/><br /> /// 将 <see cref="DateOnly"/> 转换为 <see cref="DateInfo"/>。 /// </summary> /// <param name="di"></param> public static implicit operator DateOnly(DateInfo di) { return di.ToDateOnly(); } /// <summary> /// Convert <see cref="DateInfo"/> to <see cref="DateOnly"/><br /> /// 将 <see cref="DateInfo"/> 转换为 <see cref="DateOnly"/>。 /// </summary> /// <param name="dt"></param> public static implicit operator DateInfo(DateOnly dt) { return FromDateOnly(dt); } /// <summary> /// + /// </summary> /// <param name="d"></param> /// <param name="t"></param> /// <returns></returns> public static DateInfo operator +(DateInfo d, TimeSpan t) { return new(d._internalDateTime + t); } /// <summary> /// - /// </summary> /// <param name="d"></param> /// <param name="t"></param> /// <returns></returns> public static DateInfo operator -(DateInfo d, TimeSpan t) { return new(d._internalDateTime - t); } /// <summary> /// &gt; /// </summary> /// <param name="d1"></param> /// <param name="d2"></param> /// <returns></returns> public static bool operator >(DateInfo d1, DateInfo d2) { if (d1 is null || d2 is null) return false; if (d1.Year > d2.Year) return true; if (d1.Year < d2.Year) return false; if (d1.Month > d2.Month) return true; if (d1.Month < d2.Month) return false; return d1.Day > d2.Day; } /// <summary> /// &gt; /// </summary> /// <param name="d"></param> /// <param name="dt"></param> /// <returns></returns> public static bool operator >(DateInfo d, DateTime dt) { if (d is null) return false; if (d.Year > dt.Year) return true; if (d.Year < dt.Year) return false; if (d.Month > dt.Month) return true; if (d.Month < dt.Month) return false; return d.Day > dt.Day; } /// <summary> /// &gt; /// </summary> /// <param name="d"></param> /// <param name="dt"></param> /// <returns></returns> public static bool operator >(DateInfo d, DateOnly dt) { if (d is null) return false; if (d.Year > dt.Year) return true; if (d.Year < dt.Year) return false; if (d.Month > dt.Month) return true; if (d.Month < dt.Month) return false; return d.Day > dt.Day; } /// <summary> /// &lt; /// </summary> /// <param name="d1"></param> /// <param name="d2"></param> /// <returns></returns> public static bool operator <(DateInfo d1, DateInfo d2) { if (d1 is null || d2 is null) return false; if (d1.Year < d2.Year) return true; if (d1.Year > d2.Year) return false; if (d1.Month < d2.Month) return true; if (d1.Month > d2.Month) return false; return d1.Day < d2.Day; } /// <summary> /// &lt; /// </summary> /// <param name="d"></param> /// <param name="dt"></param> /// <returns></returns> public static bool operator <(DateInfo d, DateTime dt) { if (d is null) return false; if (d.Year < dt.Year) return true; if (d.Year > dt.Year) return false; if (d.Month < dt.Month) return true; if (d.Month > dt.Month) return false; return d.Day < dt.Day; } /// <summary> /// &lt; /// </summary> /// <param name="d"></param> /// <param name="dt"></param> /// <returns></returns> public static bool operator <(DateInfo d, DateOnly dt) { if (d is null) return false; if (d.Year < dt.Year) return true; if (d.Year > dt.Year) return false; if (d.Month < dt.Month) return true; if (d.Month > dt.Month) return false; return d.Day < dt.Day; } /// <summary> /// &gt;= /// </summary> /// <param name="d1"></param> /// <param name="d2"></param> /// <returns></returns> public static bool operator >=(DateInfo d1, DateInfo d2) { if (d1 is null || d2 is null) return false; return !(d1 < d2); } /// <summary> /// &gt;= /// </summary> /// <param name="d"></param> /// <param name="dt"></param> /// <returns></returns> public static bool operator >=(DateInfo d, DateTime dt) { if (d is null) return false; return !(d < dt); } /// <summary> /// &gt;= /// </summary> /// <param name="d"></param> /// <param name="dt"></param> /// <returns></returns> public static bool operator >=(DateInfo d, DateOnly dt) { if (d is null) return false; return !(d < dt); } /// <summary> /// &lt;= /// </summary> /// <param name="d1"></param> /// <param name="d2"></param> /// <returns></returns> public static bool operator <=(DateInfo d1, DateInfo d2) { if (d1 is null || d2 is null) return false; return !(d1 > d2); } /// <summary> /// &lt;= /// </summary> /// <param name="d"></param> /// <param name="dt"></param> /// <returns></returns> public static bool operator <=(DateInfo d, DateTime dt) { if (d is null) return false; return !(d > dt); } /// <summary> /// &lt;= /// </summary> /// <param name="d"></param> /// <param name="dt"></param> /// <returns></returns> public static bool operator <=(DateInfo d, DateOnly dt) { if (d is null) return false; return !(d > dt); } /// <summary> /// == /// </summary> /// <param name="d1"></param> /// <param name="d2"></param> /// <returns></returns> public static bool operator ==(DateInfo d1, DateInfo d2) { try { return d1!.Year == d2!.Year && d1.Month == d2.Month && d1.Day == d2.Day; } catch { return false; } } /// <summary> /// == /// </summary> /// <param name="d"></param> /// <param name="dt"></param> /// <returns></returns> public static bool operator ==(DateInfo d, DateTime dt) { if (d is null) return false; return d.Year == dt.Year && d.Month == dt.Month && d.Day == dt.Day; } /// <summary> /// == /// </summary> /// <param name="d"></param> /// <param name="dt"></param> /// <returns></returns> public static bool operator ==(DateInfo d, DateOnly dt) { if (d is null) return false; return d.Year == dt.Year && d.Month == dt.Month && d.Day == dt.Day; } /// <summary> /// != /// </summary> /// <param name="d1"></param> /// <param name="d2"></param> /// <returns></returns> public static bool operator !=(DateInfo d1, DateInfo d2) { if (d1 is null || d2 is null) return false; return !(d1 == d2); } /// <summary> /// != /// </summary> /// <param name="d"></param> /// <param name="dt"></param> /// <returns></returns> public static bool operator !=(DateInfo d, DateTime dt) { if (d is null) return false; return !(d == dt); } /// <summary> /// != /// </summary> /// <param name="d"></param> /// <param name="dt"></param> /// <returns></returns> public static bool operator !=(DateInfo d, DateOnly dt) { if (d is null) return false; return !(d == dt); } /// <summary> /// Equals<br /> /// 相等 /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { if (obj is null) return false; if (obj is DateInfo date) { return _internalDateTime.Equals(date._internalDateTime); } return false; } /// <summary> /// Get hashcode<br /> /// 获取哈希值 /// </summary> /// <returns></returns> public override int GetHashCode() { return Day.GetHashCode() ^ Month.GetHashCode() ^ Year.GetHashCode(); } public override string ToString() { // ReSharper disable once SpecifyACultureInStringConversionExplicitly return _internalDateTime.ToString(); } public string ToString(string format) { return _internalDateTime.ToString(format); } public string ToString(IFormatProvider provider) { return _internalDateTime.ToString(provider); } public string ToString(string format, IFormatProvider provider) { return _internalDateTime.ToString(format, provider); } public static int DaysInMonth(int year, int month) { return DateTime.DaysInMonth(year, month); } public static int DaysInYear(int year) { return DateTime.IsLeapYear(year) ? 366 : 365; } public static bool IsLeapYear(int year) => DateTime.IsLeapYear(year); /// <summary> /// To get an instance of Infinite Future Info. <br /> /// 获取一个无限未来日期信息 /// </summary> public static InfiniteFutureInfo InfiniteFuture => InfiniteFutureInfo.Instance; /// <summary> /// To get an instance of Infinite Past Info. <br /> /// 获取一个无限过去日期信息 /// </summary> public static InfinitePastInfo InfinitePast => InfinitePastInfo.Instance; /// <summary> /// Create a new instance of <see cref="DateInfo"/> from a <see cref="DateTime"/> object. <br /> /// 从一个 <see cref="DateTime"/> 对象中创建一个 <see cref="DateInfo"/> 实例 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static DateInfo FromDateTime(DateTime dt) { return new(dt); } /// <summary> /// Create a new instance of <see cref="DateInfo"/> from a <see cref="DateOnly"/> object. <br /> /// 从一个 <see cref="DateOnly"/> 对象中创建一个 <see cref="DateInfo"/> 实例 /// </summary> /// <param name="date"></param> /// <returns></returns> public static DateInfo FromDateOnly(DateOnly date) { return new(date.Year, date.Month, date.Day); } }
25.452077
119
0.522814
[ "Apache-2.0" ]
cosmos-loops/Cosmos.Standard
src/Cosmos.Extensions.DateTime/Cosmos/Date/DateInfo.cs
16,257
C#
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Protocols; namespace QianCash.Web.Configuration { public static class AuthenticationExtensions { public static IServiceCollection AddAuth0Authentication(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.ConfigurationManager = new ConfigurationManager<OpenIdConnectConfiguration>("https://dev-094y38d9.us.auth0.com/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever()); options.SaveToken = true; options.MetadataAddress = "https://dev-094y38d9.us.auth0.com/.well-known/openid-configuration"; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, RequireExpirationTime = true }; }); return services; } } }
40.363636
217
0.602477
[ "MIT" ]
swizkon/xingzen
src/QianCash.Web/Configuration/AuthenticationExtensions.cs
1,778
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Diagnostics.RemoveUnnecessaryImports; using Microsoft.CodeAnalysis.CSharp.Diagnostics.SimplifyTypeNames; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Squiggles { public class ErrorSquiggleProducerTests : AbstractSquiggleProducerTests { [Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public void ErrorTagGeneratedForError() { var spans = GetErrorSpans("class C {"); Assert.Equal(1, spans.Count()); var firstSpan = spans.First(); Assert.Equal(PredefinedErrorTypeNames.SyntaxError, firstSpan.Tag.ErrorType); } [Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public void ErrorTagGeneratedForWarning() { var spans = GetErrorSpans("class C { long x = 5l; }"); Assert.Equal(1, spans.Count()); Assert.Equal(PredefinedErrorTypeNames.Warning, spans.First().Tag.ErrorType); } [Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public void ErrorTagGeneratedForWarningAsError() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true""> <CompilationOptions ReportDiagnostic = ""Error"" /> <Document FilePath = ""Test.cs"" > class Program { void Test() { int a = 5; } } </Document> </Project> </Workspace>"; using (var workspace = TestWorkspaceFactory.CreateWorkspace(workspaceXml)) { var spans = GetErrorSpans(workspace); Assert.Equal(1, spans.Count()); Assert.Equal(PredefinedErrorTypeNames.SyntaxError, spans.First().Tag.ErrorType); } } [Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public void SuggestionTagsForUnnecessaryCode() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true""> <Document FilePath = ""Test.cs"" > // System is used - rest are unused. using System.Collections; using System; using System.Diagnostics; using System.Collections.Generic; class Program { void Test() { Int32 x = 2; // Int32 can be simplified. x += 1; } } </Document> </Project> </Workspace>"; using (var workspace = TestWorkspaceFactory.CreateWorkspace(workspaceXml)) { var analyzerMap = new Dictionary<string, DiagnosticAnalyzer[]> { { LanguageNames.CSharp, new DiagnosticAnalyzer[] { new CSharpSimplifyTypeNamesDiagnosticAnalyzer(), new CSharpRemoveUnnecessaryImportsDiagnosticAnalyzer() } } }; var spans = GetErrorSpans(workspace, analyzerMap) .OrderBy(s => s.Span.Span.Start).ToImmutableArray(); Assert.Equal(3, spans.Length); var first = spans[0]; var second = spans[1]; var third = spans[2]; Assert.Equal(PredefinedErrorTypeNames.Suggestion, first.Tag.ErrorType); Assert.Equal(CSharpFeaturesResources.RemoveUnnecessaryUsingsDiagnosticTitle, first.Tag.ToolTipContent); Assert.Equal(40, first.Span.Start); Assert.Equal(25, first.Span.Length); Assert.Equal(PredefinedErrorTypeNames.Suggestion, second.Tag.ErrorType); Assert.Equal(CSharpFeaturesResources.RemoveUnnecessaryUsingsDiagnosticTitle, second.Tag.ToolTipContent); Assert.Equal(82, second.Span.Start); Assert.Equal(60, second.Span.Length); Assert.Equal(PredefinedErrorTypeNames.Suggestion, third.Tag.ErrorType); Assert.Equal(WorkspacesResources.NameCanBeSimplified, third.Tag.ToolTipContent); Assert.Equal(196, third.Span.Start); Assert.Equal(5, third.Span.Length); } } [Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public void ErrorDoesNotCrashPastEOF() { var spans = GetErrorSpans("class C { int x ="); Assert.Equal(3, spans.Count()); } [Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public void SemanticErrorReported() { var spans = GetErrorSpans("class C : Bar { }"); Assert.Equal(1, spans.Count()); var firstSpan = spans.First(); Assert.Equal(PredefinedErrorTypeNames.SyntaxError, firstSpan.Tag.ErrorType); Assert.Contains("Bar", (string)firstSpan.Tag.ToolTipContent, StringComparison.Ordinal); } [Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public void BuildErrorZeroLengthSpan() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true""> <Document FilePath = ""Test.cs"" > class Test { } </Document> </Project> </Workspace>"; using (var workspace = TestWorkspaceFactory.CreateWorkspace(workspaceXml)) { var document = workspace.Documents.First(); var updateArgs = new DiagnosticsUpdatedArgs( new object(), workspace, workspace.CurrentSolution, document.Project.Id, document.Id, ImmutableArray.Create( CreateDiagnosticData(workspace, document, new TextSpan(0, 0)), CreateDiagnosticData(workspace, document, new TextSpan(0, 1)))); var spans = GetErrorsFromUpdateSource(workspace, document, updateArgs); Assert.Equal(1, spans.Count()); var first = spans.First(); Assert.Equal(1, first.Span.Span.Length); } } [Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public void LiveErrorZeroLengthSpan() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true""> <Document FilePath = ""Test.cs"" > class Test { } </Document> </Project> </Workspace>"; using (var workspace = TestWorkspaceFactory.CreateWorkspace(workspaceXml)) { var document = workspace.Documents.First(); var updateArgs = new DiagnosticsUpdatedArgs( new LiveId(), workspace, workspace.CurrentSolution, document.Project.Id, document.Id, ImmutableArray.Create( CreateDiagnosticData(workspace, document, new TextSpan(0, 0)), CreateDiagnosticData(workspace, document, new TextSpan(0, 1)))); var spans = GetErrorsFromUpdateSource(workspace, document, updateArgs); Assert.Equal(2, spans.Count()); var first = spans.First(); var second = spans.Last(); Assert.Equal(1, first.Span.Span.Length); Assert.Equal(1, second.Span.Span.Length); } } private class LiveId : ISupportLiveUpdate { public LiveId() { } } private static IEnumerable<ITagSpan<IErrorTag>> GetErrorSpans(params string[] content) { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(content)) { return GetErrorSpans(workspace); } } } }
36.118143
160
0.589486
[ "Apache-2.0" ]
davidfowl/roslyn
src/EditorFeatures/CSharpTest/Squiggles/ErrorSquiggleProducerTests.cs
8,560
C#
using Up.NET.Api.Webhooks; using Up.NET.Api.Webhooks.Events; using Up.NET.Api.Webhooks.Logs; using Up.NET.Models; namespace Up.NET.Api; public partial class UpApi { public async Task<UpResponse<PaginatedDataResponse<WebhookResource>>> GetWebhooksAsync(int? pageSize = null) { var queryParams = new Dictionary<string, string>(); if (pageSize.HasValue) { queryParams.Add("page[size]", pageSize.ToString()); } return await SendPaginatedRequestAsync<WebhookResource>(HttpMethod.Get, "/webhooks", queryParams); } public async Task<UpResponse<DataResponse<WebhookResource>>> CreateWebhookAsync(WebhookInputResource webhook) { var content = new DataWrapper<WebhookInputResource> { Data = webhook }; return await SendRequestAsync<DataResponse<WebhookResource>>(HttpMethod.Post, "/webhooks", content: content); } public async Task<UpResponse<DataResponse<WebhookResource>>> GetWebhooksAsync(string id) => await SendRequestAsync<DataResponse<WebhookResource>>(HttpMethod.Get, $"/webhooks/{id}"); public async Task<UpResponse<NoResponse>> DeleteWebhookAsync(string id) => await SendRequestAsync<NoResponse>(HttpMethod.Delete, $"/webhooks/{id}"); public async Task<UpResponse<WebhookEventResource>> PingWebhookAsync(string webhookId) => await SendRequestAsync<WebhookEventResource>(HttpMethod.Post, $"/webhooks/{webhookId}/ping"); public async Task<UpResponse<PaginatedDataResponse<WebhookDeliveryLogResource>>> GetWebhookLogsAsync( string webhookId) => await SendPaginatedRequestAsync<WebhookDeliveryLogResource>(HttpMethod.Get, $"/webhooks/{webhookId}/logs"); }
39.5
118
0.721519
[ "MIT" ]
Hona/Up.NET
Up.NET/Api/WebhooksApi.cs
1,740
C#
using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace Uragano.Abstractions { public class AsyncLock { private object _reentrancy = new object(); private int _reentrances = 0; //We are using this SemaphoreSlim like a posix condition variable //we only want to wake waiters, one or more of whom will try to obtain a different lock to do their thing //so long as we can guarantee no wakes are missed, the number of awakees is not important //ideally, this would be "friend" for access only from InnerLock, but whatever. internal SemaphoreSlim _retry = new SemaphoreSlim(0, 1); //We do not have System.Threading.Thread.* on .NET Standard without additional dependencies //Work around is easy: create a new ThreadLocal<T> with a random value and this is our thread id :) private static readonly long UnlockedThreadId = 0; //"owning" thread id when unlocked internal long _owningId = UnlockedThreadId; private static int _globalThreadCounter; private static readonly ThreadLocal<int> _threadId = new ThreadLocal<int>(() => Interlocked.Increment(ref _globalThreadCounter)); //We generate a unique id from the thread ID combined with the task ID, if any public static long ThreadId => (long)(((ulong)_threadId.Value) << 32) | ((uint)(Task.CurrentId ?? 0)); struct InnerLock : IDisposable { private readonly AsyncLock _parent; #if DEBUG private bool _disposed; #endif internal InnerLock(AsyncLock parent) { _parent = parent; #if DEBUG _disposed = false; #endif } internal async Task ObtainLockAsync() { while (!TryEnter()) { //we need to wait for someone to leave the lock before trying again await _parent._retry.WaitAsync(); } } internal async Task ObtainLockAsync(CancellationToken ct) { while (!TryEnter()) { //we need to wait for someone to leave the lock before trying again await _parent._retry.WaitAsync(ct); } } internal void ObtainLock() { while (!TryEnter()) { //we need to wait for someone to leave the lock before trying again _parent._retry.Wait(); } } private bool TryEnter() { lock (_parent._reentrancy) { Debug.Assert((_parent._owningId == UnlockedThreadId) == (_parent._reentrances == 0)); if (_parent._owningId != UnlockedThreadId && _parent._owningId != AsyncLock.ThreadId) { //another thread currently owns the lock return false; } //we can go in Interlocked.Increment(ref _parent._reentrances); _parent._owningId = AsyncLock.ThreadId; return true; } } public void Dispose() { #if DEBUG Debug.Assert(!_disposed); _disposed = true; #endif lock (_parent._reentrancy) { Interlocked.Decrement(ref _parent._reentrances); if (_parent._reentrances == 0) { //the owning thread is always the same so long as we are in a nested stack call //we reset the owning id to null only when the lock is fully unlocked _parent._owningId = UnlockedThreadId; if (_parent._retry.CurrentCount == 0) { _parent._retry.Release(); } } } } } public IDisposable Lock() { var @lock = new InnerLock(this); @lock.ObtainLock(); return @lock; } public async Task<IDisposable> LockAsync() { var @lock = new InnerLock(this); await @lock.ObtainLockAsync(); return @lock; } public async Task<IDisposable> LockAsync(CancellationToken ct) { var @lock = new InnerLock(this); await @lock.ObtainLockAsync(ct); return @lock; } } }
36.307692
137
0.524153
[ "MIT" ]
1100100/Uragano
src/Uragano.Abstract/AsyncLock.cs
4,722
C#
using MasterServerToolkit.Networking; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace MasterServerToolkit.MasterServer { public class MstProperties { private Dictionary<string, string> properties; public MstProperties() { properties = new Dictionary<string, string>(); } public MstProperties(Dictionary<string, string> options) { this.properties = new Dictionary<string, string>(); Append(options); } public MstProperties(MstProperties options) { this.properties = new Dictionary<string, string>(); Append(options); } public bool Remove(string key) { return properties.Remove(key); } public void Clear() { properties.Clear(); } private void AddToOptions(string key, object value) { if (Has(key)) { throw new Exception($"You have already added value with key {key}"); } SetToOptions(key, value); } private void SetToOptions(string key, object value) { properties[key] = value.ToString(); } public void Append(MstProperties options) { if (options != null) Append(options.ToDictionary()); } public void Append(Dictionary<string, string> options) { if (options != null) foreach (var kvp in options) { AddToOptions(kvp.Key, kvp.Value); } } public bool Has(string key) { return properties.ContainsKey(key); } public bool IsValueEmpty(string key) { if (!Has(key)) { return true; } else { return string.IsNullOrEmpty(AsString(key).Trim()); } } public void Add(string key) { AddToOptions(key, string.Empty); } public void Add(string key, int value) { AddToOptions(key, value); } public void Set(string key, int value) { SetToOptions(key, value); } public void Add(string key, float value) { AddToOptions(key, value); } public void Set(string key, float value) { SetToOptions(key, value); } public void Add(string key, double value) { AddToOptions(key, value); } public void Set(string key, double value) { SetToOptions(key, value); } public void Add(string key, decimal value) { AddToOptions(key, value); } public void Set(string key, decimal value) { SetToOptions(key, value); } public void Add(string key, bool value) { AddToOptions(key, value); } public void Set(string key, bool value) { SetToOptions(key, value); } public void Add(string key, short value) { AddToOptions(key, value); } public void Set(string key, short value) { SetToOptions(key, value); } public void Add(string key, byte value) { AddToOptions(key, value); } public void Set(string key, byte value) { SetToOptions(key, value); } public void Add(string key, string value) { AddToOptions(key, value); } public void Set(string key, string value) { SetToOptions(key, value); } public string AsString(string key, string defValue = "") { if (!Has(key)) { return defValue; } return properties[key]; } public int AsInt(string key, int defValue = 0) { if (!Has(key)) { return defValue; } return Convert.ToInt32(properties[key]); } public float AsFloat(string key, float defValue = 0f) { if (!Has(key)) { return defValue; } return Convert.ToSingle(properties[key]); } public double AsDouble(string key, double defValue = 0d) { if (!Has(key)) { return defValue; } return Convert.ToDouble(properties[key]); } public decimal AsDecimal(string key, decimal defValue = 0) { if (!Has(key)) { return defValue; } return Convert.ToDecimal(properties[key]); } public bool AsBool(string key, bool defValue = false) { if (!Has(key)) { return defValue; } return Convert.ToBoolean(properties[key]); } public short AsShort(string key, short defValue = 0) { if (!Has(key)) { return defValue; } return Convert.ToInt16(properties[key]); } public byte AsByte(string key, byte defValue = 0) { if (!Has(key)) { return defValue; } return Convert.ToByte(properties[key]); } public Dictionary<string, string> ToDictionary() { return properties; } public static MstProperties FromDictionary(IDictionary dictionary) { var properties = new MstProperties(); foreach(var key in dictionary.Keys) { properties.Set(key.ToString(), dictionary[key].ToString()); } return properties; } public byte[] ToBytes() { return properties.ToBytes(); } public static MstProperties FromBytes(byte[] data) { return new MstProperties(new Dictionary<string, string>().FromBytes(data)); } public string ToReadableString(string itemsSeparator = "; ", string kvpSeparator = " : ") { return ToDictionary().ToReadableString(itemsSeparator, kvpSeparator); } public override string ToString() { return ToReadableString(); } } }
23.176471
97
0.485667
[ "MIT" ]
itsnotyoutoday/MST
Assets/MasterServerToolkit/Tools/UI/Scripts/Generic/MstProperties.cs
6,700
C#
/* * Fatture in Cloud API v2 - API Reference * * Connect your software with Fatture in Cloud, the invoicing platform chosen by more than 400.000 businesses in Italy. The Fatture in Cloud API is based on REST, and makes possible to interact with the user related data prior authorization via OAuth2 protocol. * * The version of the OpenAPI document: 2.0.15 * Contact: info@fattureincloud.it * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = It.FattureInCloud.Sdk.Client.OpenAPIDateConverter; namespace It.FattureInCloud.Sdk.Model { /// <summary> /// CompanyInfoPlanInfo /// </summary> [DataContract(Name = "CompanyInfo_plan_info")] public partial class CompanyInfoPlanInfo : IEquatable<CompanyInfoPlanInfo>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="CompanyInfoPlanInfo" /> class. /// </summary> /// <param name="limits">limits.</param> /// <param name="functions">functions.</param> /// <param name="functionsStatus">functionsStatus.</param> public CompanyInfoPlanInfo(CompanyInfoPlanInfoLimits limits = default(CompanyInfoPlanInfoLimits), CompanyInfoPlanInfoFunctions functions = default(CompanyInfoPlanInfoFunctions), CompanyInfoPlanInfoFunctionsStatus functionsStatus = default(CompanyInfoPlanInfoFunctionsStatus)) { this._Limits = limits; if (this.Limits != null) this._flagLimits = true; this._Functions = functions; if (this.Functions != null) this._flagFunctions = true; this._FunctionsStatus = functionsStatus; if (this.FunctionsStatus != null) this._flagFunctionsStatus = true; } /// <summary> /// Gets or Sets Limits /// </summary> [DataMember(Name = "limits", EmitDefaultValue = true)] public CompanyInfoPlanInfoLimits Limits { get{ return _Limits;} set { _Limits = value; _flagLimits = true; } } private CompanyInfoPlanInfoLimits _Limits; private bool _flagLimits; /// <summary> /// Returns false as Limits should not be serialized given that it's read-only. /// </summary> /// <returns>false (boolean)</returns> public bool ShouldSerializeLimits() { return _flagLimits; } /// <summary> /// Gets or Sets Functions /// </summary> [DataMember(Name = "functions", EmitDefaultValue = true)] public CompanyInfoPlanInfoFunctions Functions { get{ return _Functions;} set { _Functions = value; _flagFunctions = true; } } private CompanyInfoPlanInfoFunctions _Functions; private bool _flagFunctions; /// <summary> /// Returns false as Functions should not be serialized given that it's read-only. /// </summary> /// <returns>false (boolean)</returns> public bool ShouldSerializeFunctions() { return _flagFunctions; } /// <summary> /// Gets or Sets FunctionsStatus /// </summary> [DataMember(Name = "functions_status", EmitDefaultValue = true)] public CompanyInfoPlanInfoFunctionsStatus FunctionsStatus { get{ return _FunctionsStatus;} set { _FunctionsStatus = value; _flagFunctionsStatus = true; } } private CompanyInfoPlanInfoFunctionsStatus _FunctionsStatus; private bool _flagFunctionsStatus; /// <summary> /// Returns false as FunctionsStatus should not be serialized given that it's read-only. /// </summary> /// <returns>false (boolean)</returns> public bool ShouldSerializeFunctionsStatus() { return _flagFunctionsStatus; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class CompanyInfoPlanInfo {\n"); sb.Append(" Limits: ").Append(Limits).Append("\n"); sb.Append(" Functions: ").Append(Functions).Append("\n"); sb.Append(" FunctionsStatus: ").Append(FunctionsStatus).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as CompanyInfoPlanInfo); } /// <summary> /// Returns true if CompanyInfoPlanInfo instances are equal /// </summary> /// <param name="input">Instance of CompanyInfoPlanInfo to be compared</param> /// <returns>Boolean</returns> public bool Equals(CompanyInfoPlanInfo input) { if (input == null) { return false; } return ( this.Limits == input.Limits || (this.Limits != null && this.Limits.Equals(input.Limits)) ) && ( this.Functions == input.Functions || (this.Functions != null && this.Functions.Equals(input.Functions)) ) && ( this.FunctionsStatus == input.FunctionsStatus || (this.FunctionsStatus != null && this.FunctionsStatus.Equals(input.FunctionsStatus)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Limits != null) { hashCode = (hashCode * 59) + this.Limits.GetHashCode(); } if (this.Functions != null) { hashCode = (hashCode * 59) + this.Functions.GetHashCode(); } if (this.FunctionsStatus != null) { hashCode = (hashCode * 59) + this.FunctionsStatus.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
35.865471
283
0.570268
[ "MIT" ]
fattureincloud/fattureincloud-csharp-sdk
src/It.FattureInCloud.Sdk/Model/CompanyInfoPlanInfo.cs
7,998
C#
using Microsoft.OData.Edm; using OdataToEntity.ModelBuilder; using OdataToEntity.Test.Model; using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace OdataToEntity.Test { public abstract class DbFixtureInitDb : DbFixture { private bool _initialized; private readonly bool _useRelationalNulls; protected DbFixtureInitDb(Type _, bool useRelationalNulls, ModelBoundTestKind modelBoundTestKind) : base(CreateOeEdmModel(useRelationalNulls), modelBoundTestKind, useRelationalNulls) { _useRelationalNulls = useRelationalNulls; } public override OrderContext CreateContext() { return new OrderContext(OrderContextOptions.Create(_useRelationalNulls)); } internal static EdmModel CreateOeEdmModel(bool useRelationalNulls) { var dataAdapter = new OrderDataAdapter(true, useRelationalNulls); OeEdmModelMetadataProvider metadataProvider = OrderDataAdapter.CreateMetadataProvider(); bool allowCache = TestHelper.GetQueryCache(dataAdapter).AllowCache; var order2DataAdapter = new Order2DataAdapter(allowCache, useRelationalNulls); var refModel = new OeEdmModelBuilder(dataAdapter, metadataProvider).BuildEdmModel(); return order2DataAdapter.BuildEdmModel(refModel); } public override async Task Execute<T, TResult>(QueryParameters<T, TResult> parameters) { Task t1 = base.Execute(parameters); Task t2 = base.Execute(parameters); await Task.WhenAll(t1, t2).ConfigureAwait(false); } public override async Task Execute<T, TResult>(QueryParametersScalar<T, TResult> parameters) { Task t1 = base.Execute(parameters); Task t2 = base.Execute(parameters); await Task.WhenAll(t1, t2).ConfigureAwait(false); } public async override Task Initalize() { if (_initialized) return; _initialized = true; var parser = new OeParser(new Uri("http://dummy/"), base.OeEdmModel); await parser.ExecuteOperationAsync(base.ParseUri("ResetDb"), OeRequestHeaders.JsonDefault, null, new MemoryStream(), CancellationToken.None).ConfigureAwait(false); await DbFixture.ExecuteBatchAsync(base.OeEdmModel, "Add").ConfigureAwait(false); } } public abstract class ManyColumnsFixtureInitDb : DbFixture { private bool _initialized; private readonly bool _useRelationalNulls; protected ManyColumnsFixtureInitDb(Type _, bool useRelationalNulls, ModelBoundTestKind modelBoundTestKind) : base(DbFixtureInitDb.CreateOeEdmModel(useRelationalNulls), modelBoundTestKind, useRelationalNulls) { _useRelationalNulls = useRelationalNulls; } public override OrderContext CreateContext() { return new OrderContext(OrderContextOptions.Create(_useRelationalNulls)); ; } public override async Task Execute<T, TResult>(QueryParameters<T, TResult> parameters) { Task t1 = base.Execute(parameters); Task t2 = base.Execute(parameters); await Task.WhenAll(t1, t2).ConfigureAwait(false); } public override async Task Execute<T, TResult>(QueryParametersScalar<T, TResult> parameters) { Task t1 = base.Execute(parameters); Task t2 = base.Execute(parameters); await Task.WhenAll(t1, t2).ConfigureAwait(false); } public async override Task Initalize() { if (_initialized) return; _initialized = true; var parser = new OeParser(new Uri("http://dummy/"), base.OeEdmModel); await parser.ExecuteOperationAsync(base.ParseUri("ResetManyColumns"), OeRequestHeaders.JsonDefault, null, new MemoryStream(), CancellationToken.None).ConfigureAwait(false); await DbFixture.ExecuteBatchAsync(base.OeEdmModel, "ManyColumns").ConfigureAwait(false); } } }
42.948454
184
0.667787
[ "MIT" ]
DawidPotgieter/OdataToEntity
test/OdataToEntity.Test.EfCore.SqlServer/DbFixtureInitDb.cs
4,168
C#
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace IdentityStandaloneMfa.Data; public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } }
24.692308
80
0.766355
[ "MIT" ]
damienbod/AspNetCoreAuthorizationCodeFlow
IdentityStandaloneMfa/Data/ApplicationDbContext.cs
323
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace GEMSNT.GEMSBinaryLoader { class GemsBin { public static bool LoadGemsBin(string path) { try { if (path.EndsWith(".bin")) { byte[] bytes = File.ReadAllBytes(path); System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(bytes); return true; } else { Console.WriteLine("Not a .bin file"); return false; } } catch { Console.WriteLine("Generic error. (Too big?)"); return false; } } } }
25.84375
93
0.434099
[ "MIT" ]
sparksammy/GEMS-NT
GEMSNT/GemsBin.cs
829
C#
using System; namespace CSTest.Readonly { public class ReadonlyTest { public void Test() { var point1 = new PointNoReadonly { X = 1, Y = 1 }; var point2 = new Point { X = 1, Y = 1 }; Console.WriteLine(">>>>>PointNoReadonly<<<<<"); Console.WriteLine(point1); Console.WriteLine(point1); Console.WriteLine(point1); Console.WriteLine(point1); Console.WriteLine(point1); Console.WriteLine(">>>>>PointNoReadonly<<<<<"); Console.WriteLine(">>>>>Point<<<<<"); Console.WriteLine(point2); Console.WriteLine(point2); Console.WriteLine(point2); Console.WriteLine(point2); Console.WriteLine(point2); Console.WriteLine(">>>>>Point<<<<<"); } struct PointNoReadonly { public double X { get; set; } public double Y { get; set; } public double Distance => Math.Sqrt(X * X + Y * Y); public double C { get; } public void Translate(int xOffset, int yOffset) { X += xOffset; Y += yOffset; } public override string ToString() { return $"({X},{Y}) is {Distance} from origin"; } } struct Point { public double X { get; set; } public double Y { get; set; } public readonly double Distance => Math.Sqrt(X * X + Y * Y); public double C { get; } //public readonly void Translate(int xOffset, int yOffset) //{ // X += xOffset; // Y += yOffset; //} public override string ToString() { return $"({X},{Y}) is {Distance} from origin"; } } } }
24.963415
72
0.434294
[ "MIT" ]
marchers/amadeus-learning
src/CSharp8/CSTest/Readonly/ReadonlyTest.cs
2,049
C#
using System; namespace _2._2 { public class List { public Node Head { get; set; } public int Length { get; set; } public bool IsEmpty => Length == 0; private bool IsContained(int position) => !(IsEmpty || position > Length || position < 1); public bool IsContainedByValue(string value) { var temp = Head; for (int i = 1; i <= Length; ++i) { if (temp.Value == value) { return true; } if (temp.Next != null) { temp = temp.Next; } } return false; } public void Print() { if (IsEmpty) { Console.WriteLine("List is empty"); } else { var temp = Head; for (int i = 0; i < Length; ++i) { Console.WriteLine($"Value: {temp.Value}, position: {i}"); if (temp.Next != null) { temp = temp.Next; } } } } public int PositionByValue(string value) { var temp = Head; for (int i = 1; i <= Length; ++i) { if (temp.Value == value) { return i; } temp = temp.Next; } return 0; } public void Add(string value, int position) { if (IsEmpty) { Head = new Node(value); ++Length; return; } if (position > Length + 1 || position < 1) { throw new InvalidOperationException("Invalid position"); } var newElement = new Node(value); if (position == 1) { newElement.Next = Head; Head = newElement; ++Length; } else { var temp = Head; for (int i = 1; i < position - 1; ++i) { if (temp.Next != null) { temp = temp.Next; } } newElement.Next = temp.Next; temp.Next = newElement; ++Length; } } public void Delete(int position) { if (IsEmpty) { throw new InvalidOperationException("List is empty"); } if (!IsContained(position)) { throw new InvalidOperationException("Invalid position"); } if (position == 1) { if (Length == 1) { Head = null; } else { Head = Head.Next; } } else { var temp = Head; for (int i = 1; i < position - 1; ++i) { temp = temp.Next; } if (position == Length) { temp.Next = null; } else { temp.Next = temp.Next.Next; } } --Length; } public string GetValue(int position) { if (IsEmpty) { throw new InvalidOperationException("List is empty"); } if (!IsContained(position)) { throw new InvalidOperationException("Invalid position"); } var temp = Head; int currentPosition; for (currentPosition = 1; currentPosition < position; ++currentPosition) { temp = temp.Next; } return temp.Value; } public void SetValue(string value, int position) { if (IsEmpty) { throw new InvalidOperationException("List is empty"); } if (!IsContained(position)) { throw new InvalidOperationException("Invalid position"); } var temp = Head; for (int i = 1; i < position; ++i) { temp = temp.Next; } temp.Value = value; } } }
26.435028
98
0.353281
[ "Apache-2.0" ]
yuniyakim/Homework
Semester2/Homework2/2.2/2.2/List.cs
4,681
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; using System.Management.Automation.Host; using System.Management.Automation.Runspaces; namespace Microsoft.PowerShell.EditorServices { /// <summary> /// Provides a handle to the runspace that is managed by /// a PowerShellContext. The holder of this handle. /// </summary> public class RunspaceHandle : IDisposable { private PowerShellContext powerShellContext; /// <summary> /// Gets the runspace that is held by this handle. /// </summary> public Runspace Runspace { get { return ((IHostSupportsInteractiveSession)this.powerShellContext).Runspace; } } internal bool IsReadLine { get; } /// <summary> /// Initializes a new instance of the RunspaceHandle class using the /// given runspace. /// </summary> /// <param name="powerShellContext">The PowerShellContext instance which manages the runspace.</param> public RunspaceHandle(PowerShellContext powerShellContext) : this(powerShellContext, false) { } internal RunspaceHandle(PowerShellContext powerShellContext, bool isReadLine) { this.powerShellContext = powerShellContext; this.IsReadLine = isReadLine; } /// <summary> /// Disposes the RunspaceHandle once the holder is done using it. /// Causes the handle to be released back to the PowerShellContext. /// </summary> public void Dispose() { // Release the handle and clear the runspace so that // no further operations can be performed on it. this.powerShellContext.ReleaseRunspaceHandle(this); } } }
31.803279
110
0.628866
[ "MIT" ]
Benny1007/PowerShellEditorServices
src/PowerShellEditorServices/Session/RunspaceHandle.cs
1,940
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.Web.V20210101.Outputs { /// <summary> /// The configuration settings of the storage of the tokens if blob storage is used. /// </summary> [OutputType] public sealed class BlobStorageTokenStoreResponse { /// <summary> /// The name of the app setting containing the SAS URL of the blob storage containing the tokens. /// </summary> public readonly string? SasUrlSettingName; [OutputConstructor] private BlobStorageTokenStoreResponse(string? sasUrlSettingName) { SasUrlSettingName = sasUrlSettingName; } } }
30.290323
105
0.684771
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Web/V20210101/Outputs/BlobStorageTokenStoreResponse.cs
939
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IdentityServer4.Events; using IdentityServer4.Extensions; using IdentityServer4.Services; using IdentityServer4.Stores; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace Sereno.STS.UI.Pages.Grants { public class IndexModel : PageModel { private readonly IEventService _events; private readonly IClientStore _clients; private readonly IResourceStore _resources; private readonly IIdentityServerInteractionService _interaction; private readonly ILogger<IndexModel> _logger; public IEnumerable<GrantViewModel> Grants { get; set; } public IndexModel(ILogger<IndexModel> logger, IIdentityServerInteractionService interaction, IEventService events, IClientStore clients, IResourceStore resources) { this._logger = logger; this._interaction = interaction; this._events = events; this._clients = clients; this._resources = resources; } public async Task<IActionResult> OnGetAsync() { await this.BuildViewModelAsync(); return this.Page(); } [ValidateAntiForgeryToken] public async Task<IActionResult> PostAsync(string clientId) { await this._interaction.RevokeUserConsentAsync(clientId); await this._events.RaiseAsync(new GrantsRevokedEvent(this.User.GetSubjectId(), clientId)); return this.RedirectToPage("Index"); } private async Task BuildViewModelAsync() { var grants = await this._interaction.GetAllUserGrantsAsync(); var list = new List<GrantViewModel>(); foreach(var grant in grants) { var client = await this._clients.FindClientByIdAsync(grant.ClientId); if (client != null) { var resources = await this._resources.FindResourcesByScopeAsync(grant.Scopes); var item = new GrantViewModel() { ClientId = client.ClientId, ClientName = client.ClientName ?? client.ClientId, ClientLogoUrl = client.LogoUri, ClientUrl = client.ClientUri, Description = grant.Description, Created = grant.CreationTime, Expires = grant.Expiration, IdentityGrantNames = resources.IdentityResources.Select(x => x.DisplayName ?? x.Name).ToArray(), ApiGrantNames = resources.ApiScopes.Select(x => x.DisplayName ?? x.Name).ToArray() }; list.Add(item); } } this.Grants = list; } public class GrantViewModel { public string ClientId { get; set; } public string ClientName { get; set; } public string ClientUrl { get; set; } public string ClientLogoUrl { get; set; } public string Description { get; set; } public DateTime Created { get; set; } public DateTime? Expires { get; set; } public IEnumerable<string> IdentityGrantNames { get; set; } public IEnumerable<string> ApiGrantNames { get; set; } } } }
35.67
120
0.590973
[ "MIT" ]
sergiomcalzada/sereno
src/Sereno.STS.UI/Pages/Grants/Index.cshtml.cs
3,569
C#
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using PureCloudPlatform.Client.V2.Client; namespace PureCloudPlatform.Client.V2.Model { /// <summary> /// Trustee /// </summary> [DataContract] public partial class Trustee : IEquatable<Trustee> { /// <summary> /// Initializes a new instance of the <see cref="Trustee" /> class. /// </summary> [JsonConstructorAttribute] protected Trustee() { } /// <summary> /// Initializes a new instance of the <see cref="Trustee" /> class. /// </summary> /// <param name="Enabled">If disabled no trustee user will have access, even if they were previously added. (required).</param> /// <param name="CreatedBy">User that created trust..</param> /// <param name="Organization">Organization associated with this trust..</param> public Trustee(bool? Enabled = null, OrgUser CreatedBy = null, Organization Organization = null) { this.Enabled = Enabled; this.CreatedBy = CreatedBy; this.Organization = Organization; } /// <summary> /// Organization Id for this trust. /// </summary> /// <value>Organization Id for this trust.</value> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; private set; } /// <summary> /// If disabled no trustee user will have access, even if they were previously added. /// </summary> /// <value>If disabled no trustee user will have access, even if they were previously added.</value> [DataMember(Name="enabled", EmitDefaultValue=false)] public bool? Enabled { get; set; } /// <summary> /// Date Trust was created. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss.SSSZ /// </summary> /// <value>Date Trust was created. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss.SSSZ</value> [DataMember(Name="dateCreated", EmitDefaultValue=false)] public DateTime? DateCreated { get; private set; } /// <summary> /// User that created trust. /// </summary> /// <value>User that created trust.</value> [DataMember(Name="createdBy", EmitDefaultValue=false)] public OrgUser CreatedBy { get; set; } /// <summary> /// Organization associated with this trust. /// </summary> /// <value>Organization associated with this trust.</value> [DataMember(Name="organization", EmitDefaultValue=false)] public Organization Organization { get; set; } /// <summary> /// The URI for this object /// </summary> /// <value>The URI for this object</value> [DataMember(Name="selfUri", EmitDefaultValue=false)] public string SelfUri { get; private set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Trustee {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Enabled: ").Append(Enabled).Append("\n"); sb.Append(" DateCreated: ").Append(DateCreated).Append("\n"); sb.Append(" CreatedBy: ").Append(CreatedBy).Append("\n"); sb.Append(" Organization: ").Append(Organization).Append("\n"); sb.Append(" SelfUri: ").Append(SelfUri).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as Trustee); } /// <summary> /// Returns true if Trustee instances are equal /// </summary> /// <param name="other">Instance of Trustee to be compared</param> /// <returns>Boolean</returns> public bool Equals(Trustee other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return true && ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Enabled == other.Enabled || this.Enabled != null && this.Enabled.Equals(other.Enabled) ) && ( this.DateCreated == other.DateCreated || this.DateCreated != null && this.DateCreated.Equals(other.DateCreated) ) && ( this.CreatedBy == other.CreatedBy || this.CreatedBy != null && this.CreatedBy.Equals(other.CreatedBy) ) && ( this.Organization == other.Organization || this.Organization != null && this.Organization.Equals(other.Organization) ) && ( this.SelfUri == other.SelfUri || this.SelfUri != null && this.SelfUri.Equals(other.SelfUri) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.Enabled != null) hash = hash * 59 + this.Enabled.GetHashCode(); if (this.DateCreated != null) hash = hash * 59 + this.DateCreated.GetHashCode(); if (this.CreatedBy != null) hash = hash * 59 + this.CreatedBy.GetHashCode(); if (this.Organization != null) hash = hash * 59 + this.Organization.GetHashCode(); if (this.SelfUri != null) hash = hash * 59 + this.SelfUri.GetHashCode(); return hash; } } } }
32.120968
136
0.490836
[ "MIT" ]
nmusco/platform-client-sdk-dotnet
build/src/PureCloudPlatform.Client.V2/Model/Trustee.cs
7,966
C#
using System; using System.Threading; using System.Threading.Tasks; using Android.Content; using Android.Graphics; using FFImageLoading.Drawables; using FFImageLoading.Views; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; namespace FFImageLoading.Forms.Droid { public class FFImageSourceHandler : IImageSourceHandler { public async Task<Bitmap> LoadImageAsync(ImageSource imagesource, Context context, CancellationToken cancelationToken = default(CancellationToken)) { var ffImageSource = imagesource as FFImageSource; ffImageSource.LoadingStarted(); ffImageSource.RegisterCancelToken(cancelationToken); SelfDisposingBitmapDrawable bitmapDrawable = null; try { bitmapDrawable = await Task.Run(() => ffImageSource.TaskParameter.AsBitmapDrawableAsync(), cancelationToken).ConfigureAwait(false); ffImageSource.LoadingCompleted(false); } catch (OperationCanceledException) { ffImageSource.LoadingCompleted(true); throw; } return bitmapDrawable.Bitmap; } } }
30.871795
155
0.671927
[ "MIT" ]
muak/FFImageSource
FFImageSource.Droid/FFImageSourceHandler.cs
1,206
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using DotVVM.Framework.ViewModel; namespace DotVVM.Samples.BasicSamples.ViewModels.ControlSamples.EnabledProperty { public class EnabledPropertyViewModel : DotvvmViewModelBase { //comboBox public string[] Fruits { get; set; } = { "Apple", "Banana", "Orange" }; public string SelectedFruit { get; set; } public bool ComboEnabled { get; set; } = true; //TextBox public string Text { get; set; } public bool TextEnabled { get; set; } = true; //RadioButton public bool RadioButton1 { get; set; } = true; public bool RadioButton2 { get; set; } public bool RadioEnabled { get; set; } = true; //CheckBox public bool CheckBoxChecked { get; set; } public bool CheckEnabled { get; set; } = true; //ListBox public string SelectedFruitFromList { get; set; } public bool ListEnabled { get; set; } = true; public void SwitchEnabledState() { CheckEnabled = !CheckEnabled; ComboEnabled = !ComboEnabled; RadioEnabled = !RadioEnabled; TextEnabled = !TextEnabled; ListEnabled = !ListEnabled; } } }
26.442308
79
0.613091
[ "Apache-2.0" ]
adamjez/dotvvm
src/DotVVM.Samples.Common/ViewModels/ControlSamples/EnabledProperty/EnabledProperty.cs
1,375
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using BDFramework.ScreenView; using BDFramework.Sql; using BDFramework.UFlux; using BDFramework.UI; using Code.Game; [ScreenView((int)ScreenViewEnum.Demo1)] public class ScreenView_Demo1_Screenview : IScreenView { public int Name { get; private set; } public bool IsLoad { get; private set; } public void BeginInit() { //一定要设置为true,否则当前是未加载状态 this.IsLoad = true; //加载窗口, 0是窗口id,建议自行换成枚举 UIManager.Inst.LoadWindow( WinEnum.Win_Demo1); UIManager.Inst.ShowWindow(WinEnum.Win_Demo1); Debug.Log("进入demo1"); } public void BeginExit() { //退出设置为false,否则下次进入不会调用begininit this.IsLoad = false; // Debug.Log("退出Test Screen 1"); } public void Update(float delta) { } public void FixedUpdate(float delta) { } }
21.659091
54
0.64638
[ "Apache-2.0" ]
AlanWeekend/BDFramework.Core
Assets/Code/Game@hotfix/ScreenView/ScreenView_Demo1_Screenview.cs
1,059
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Azure.DataFactory.Inputs { public sealed class DataFlowSourceArgs : Pulumi.ResourceArgs { /// <summary> /// A `dataset` block as defined below. /// </summary> [Input("dataset")] public Input<Inputs.DataFlowSourceDatasetArgs>? Dataset { get; set; } /// <summary> /// The description for the Data Flow Source. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// A `linked_service` block as defined below. /// </summary> [Input("linkedService")] public Input<Inputs.DataFlowSourceLinkedServiceArgs>? LinkedService { get; set; } /// <summary> /// The name for the Data Flow Source. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; /// <summary> /// A `schema_linked_service` block as defined below. /// </summary> [Input("schemaLinkedService")] public Input<Inputs.DataFlowSourceSchemaLinkedServiceArgs>? SchemaLinkedService { get; set; } public DataFlowSourceArgs() { } } }
30.88
101
0.609456
[ "ECL-2.0", "Apache-2.0" ]
ScriptBox99/pulumi-azure
sdk/dotnet/DataFactory/Inputs/DataFlowSourceArgs.cs
1,544
C#
//////////////////////////////////////////////////////////////////////////////////////////// // Implementation of the Google Cloud Spanner DBDriver for the LLBLGen Pro system. // (c) 2002-2019 Solutions Design, all rights reserved. // http://www.llblgen.com/ // // THIS IS NOT OPEN SOURCE SOFTWARE OF ANY KIND. // // Designed and developed by Frans Bouma. /////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Data; using System.Collections.Generic; using SD.LLBLGen.Pro.DBDriverCore; using System.Data.Common; using System.Linq; using SD.LLBLGen.Pro.Core; using SD.Tools.Algorithmia.GeneralDataStructures; using SD.Tools.BCLExtensions.CollectionsRelated; using SD.Tools.BCLExtensions.DataRelated; namespace SD.LLBLGen.Pro.DBDrivers.Spanner { /// <summary> /// Google Cloud Spanner specific implementation of DBCatalogRetriever /// </summary> public class SpannerCatalogRetriever : DBCatalogRetriever { /// <summary> /// CTor /// </summary> /// <param name="driverToUse">The driver to use.</param> public SpannerCatalogRetriever(DBDriverBase driverToUse) : base(driverToUse) { } /// <summary> /// Produces the DBSchemaRetriever instance to use for retrieving meta-data of a schema. /// </summary> /// <returns>ready to use schema retriever</returns> protected override DBSchemaRetriever CreateSchemaRetriever() { return new SpannerSchemaRetriever(this); } /// <summary> /// Retrieves all Foreign keys. /// </summary> /// <param name="catalogMetaData">The catalog meta data.</param> private void RetrieveForeignKeys(DBCatalog catalogMetaData) { if(catalogMetaData.Schemas.Count <= 0) { return; } // Spanner doesn't have FKs, but does have interleaved tables. We're going to define an FK between Parent and Child table, on the PK fields in common of both. // The parent/child relationships are in the driver. var parentChildRelationships = ((SpannerDBDriver)this.DriverToUse).ParentChildTableRelationships; // we've just 1 schema, so preselect it var schema = catalogMetaData.Schemas.First(); foreach(var kvp in parentChildRelationships) { DBTable pkTable = schema.FindTableByName(kvp.Key, true); if(pkTable == null) { continue; } HashSet<Pair<string, string>> childTables = kvp.Value; foreach(var pair in childTables) { var fkTable = schema.FindTableByName(pair.Value1, true); if(fkTable == null) { continue; } var pkSidePkFields = pkTable.PrimaryKeyFields.ToList(); var fkSidePkFields = fkTable.PrimaryKeyFields.ToList(); if(pkSidePkFields.Count > fkSidePkFields.Count) { // invalid continue; } var fkConstraint = new DBForeignKeyConstraint(string.Format("FK_{0}_{1}", pkTable.Name, fkTable.Name)); fkConstraint.AppliesToTable = fkTable; fkTable.ForeignKeyConstraints.Add(fkConstraint); switch(pair.Value2.ToLowerInvariant()) { case "cascade": fkConstraint.DeleteRuleAction = ForeignKeyRuleAction.Cascade; break; case "no action": fkConstraint.DeleteRuleAction = ForeignKeyRuleAction.NoAction; break; } for(int i = 0; i < pkSidePkFields.Count; i++) { fkConstraint.PrimaryKeyFields.Add(pkSidePkFields[i]); fkConstraint.ForeignKeyFields.Add(fkSidePkFields[i]); } } } } /// <summary> /// Produces the additional actions to perform by this catalog retriever /// </summary> /// <returns>list of additional actions to perform per schema</returns> private List<CatalogMetaDataRetrievalActionDescription> ProduceAdditionalActionsToPerform() { List<CatalogMetaDataRetrievalActionDescription> toReturn = new List<CatalogMetaDataRetrievalActionDescription>(); toReturn.Add(new CatalogMetaDataRetrievalActionDescription("Retrieving all Foreign Key Constraints", (catalog) => RetrieveForeignKeys(catalog), false)); return toReturn; } #region Class Property Declarations /// <summary> /// Gets the additional actions to perform per schema. /// </summary> protected override List<CatalogMetaDataRetrievalActionDescription> AdditionalActionsPerSchema { get { return ProduceAdditionalActionsToPerform(); } } #endregion } }
33.19084
161
0.682153
[ "MIT" ]
SolutionsDesign/LLBLGenProSpanner
Driver/SpannerCatalogRetriever.cs
4,348
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SOLIDPrinciples.Open_Close_Principle.TrueExample.Abstraction { public abstract class Coffee { public abstract double GetTotalPrice(double amount); } }
21.357143
70
0.772575
[ "MIT" ]
Xirzat1212/SOLIDPrinciples
SOLIDPrinciples/Open Close Principle/TrueExample/Abstraction/Coffee.cs
301
C#
// // TaskLoggingHelper.cs: Wrapper aroudn IBuildEngine. // // Author: // Marek Sieradzki (marek.sieradzki@gmail.com) // // (C) 2005 Marek Sieradzki // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.IO; using System.Resources; using System.Text; using Microsoft.Build.Framework; namespace Microsoft.Build.Utilities { public class TaskLoggingHelper : MarshalByRefObject { IBuildEngine buildEngine; bool hasLoggedErrors; string helpKeywordPrefix; string taskName; ResourceManager taskResources; ITask taskInstance; public TaskLoggingHelper (ITask taskInstance) { if (taskInstance == null) throw new ArgumentNullException ("taskInstance"); this.taskInstance = taskInstance; taskName = null; } [MonoTODO] public string ExtractMessageCode (string message, out string messageWithoutCodePrefix) { if (message == null) throw new ArgumentNullException ("message"); messageWithoutCodePrefix = String.Empty; return String.Empty; } [MonoTODO] public virtual string FormatResourceString (string resourceName, params object[] args) { if (resourceName == null) throw new ArgumentNullException ("resourceName"); if (taskResources == null) throw new InvalidOperationException ("Task did not register any task resources"); string resourceString = taskResources.GetString (resourceName); if (resourceString == null) throw new ArgumentException ($"No resource string found for resource named {resourceName}"); return FormatString (resourceString, args); } [MonoTODO] public virtual string FormatString (string unformatted, params object[] args) { if (unformatted == null) throw new ArgumentNullException ("unformatted"); if (args == null || args.Length == 0) return unformatted; else return String.Format (unformatted, args); } [MonoTODO] public void LogCommandLine (string commandLine) { } [MonoTODO] public void LogCommandLine (MessageImportance importance, string commandLine) { } public void LogError (string message, params object[] messageArgs) { if (message == null) throw new ArgumentNullException ("message"); ThrowInvalidOperationIf (BuildEngine == null, "Task is attempting to log before it was initialized"); BuildErrorEventArgs beea = new BuildErrorEventArgs ( null, null, BuildEngine.ProjectFileOfTaskNode, 0, 0, 0, 0, FormatString (message, messageArgs), helpKeywordPrefix, null); BuildEngine.LogErrorEvent (beea); hasLoggedErrors = true; } public void LogError (string subcategory, string errorCode, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, params object[] messageArgs) { if (message == null) throw new ArgumentNullException ("message"); ThrowInvalidOperationIf (BuildEngine == null, "Task is attempting to log before it was initialized"); BuildErrorEventArgs beea = new BuildErrorEventArgs ( subcategory, errorCode, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, FormatString (message, messageArgs), helpKeyword /*it's helpKeyword*/, null /*it's senderName*/); BuildEngine.LogErrorEvent (beea); hasLoggedErrors = true; } public void LogErrorFromException (Exception exception) { LogErrorFromException (exception, true); } public void LogErrorFromException (Exception exception, bool showStackTrace) { LogErrorFromException (exception, showStackTrace, true, String.Empty); } [MonoTODO ("Arguments @showDetail and @file are not honored")] public void LogErrorFromException (Exception exception, bool showStackTrace, bool showDetail, string file) { if (exception == null) throw new ArgumentNullException ("exception"); ThrowInvalidOperationIf (BuildEngine == null, "Task is attempting to log before it was initialized"); StringBuilder sb = new StringBuilder (); sb.Append (exception.Message); if (showStackTrace == true) sb.Append (exception.StackTrace); BuildErrorEventArgs beea = new BuildErrorEventArgs ( null, null, BuildEngine.ProjectFileOfTaskNode, 0, 0, 0, 0, sb.ToString (), exception.HelpLink, exception.Source); BuildEngine.LogErrorEvent (beea); hasLoggedErrors = true; } public void LogErrorFromResources (string messageResourceName, params object[] messageArgs) { LogErrorFromResources (null, null, null, null, 0, 0, 0, 0, messageResourceName, messageArgs); } public void LogErrorFromResources (string subcategoryResourceName, string errorCode, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string messageResourceName, params object[] messageArgs) { if (messageResourceName == null) throw new ArgumentNullException ("messageResourceName"); ThrowInvalidOperationIf (BuildEngine == null, "Task is attempting to log before it was initialized"); string subcategory = null; if (!String.IsNullOrEmpty (subcategoryResourceName)) subcategory = taskResources.GetString (subcategoryResourceName); BuildErrorEventArgs beea = new BuildErrorEventArgs ( subcategory, errorCode, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, FormatResourceString (messageResourceName, messageArgs), helpKeyword, null ); BuildEngine.LogErrorEvent (beea); hasLoggedErrors = true; } public void LogErrorWithCodeFromResources (string messageResourceName, params object[] messageArgs) { // FIXME: there should be something different than normal // LogErrorFromResources LogErrorFromResources (messageResourceName, messageArgs); } public void LogErrorWithCodeFromResources (string subcategoryResourceName, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string messageResourceName, params object[] messageArgs) { // FIXME: there should be something different than normal // LogErrorFromResources LogErrorFromResources (subcategoryResourceName, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, messageResourceName, messageArgs); } public void LogMessage (string message, params object[] messageArgs) { LogMessage (MessageImportance.Normal, message, messageArgs); } public void LogMessage (MessageImportance importance, string message, params object[] messageArgs) { if (message == null) throw new ArgumentNullException ("message"); LogMessageFromText (FormatString (message, messageArgs), importance); } public void LogMessageFromResources (string messageResourceName, params object[] messageArgs) { LogMessageFromResources (MessageImportance.Normal, messageResourceName, messageArgs); } public void LogMessageFromResources (MessageImportance importance, string messageResourceName, params object[] messageArgs) { if (messageResourceName == null) throw new ArgumentNullException ("messageResourceName"); LogMessage (importance, FormatResourceString (messageResourceName, messageArgs)); } public bool LogMessagesFromFile (string fileName) { return LogMessagesFromFile (fileName, MessageImportance.Normal); } public bool LogMessagesFromFile (string fileName, MessageImportance messageImportance) { try { StreamReader sr = new StreamReader (fileName); LogMessage (messageImportance, sr.ReadToEnd (), null); sr.Close (); return true; } catch (Exception) { return false; } } public bool LogMessagesFromStream (TextReader stream, MessageImportance messageImportance) { try { LogMessage (messageImportance, stream.ReadToEnd (), null); return true; } catch (Exception) { return false; } finally { // FIXME: should it be done here? stream.Close (); } } public bool LogMessageFromText (string lineOfText, MessageImportance messageImportance) { if (lineOfText == null) throw new ArgumentNullException ("lineOfText"); ThrowInvalidOperationIf (BuildEngine == null, "Task is attempting to log before it was initialized"); BuildMessageEventArgs bmea = new BuildMessageEventArgs ( lineOfText, helpKeywordPrefix, null, messageImportance); BuildEngine.LogMessageEvent (bmea); return true; } public void LogWarning (string message, params object[] messageArgs) { ThrowInvalidOperationIf (BuildEngine == null, "Task is attempting to log before it was initialized"); // FIXME: what about all the parameters? BuildWarningEventArgs bwea = new BuildWarningEventArgs ( null, null, BuildEngine.ProjectFileOfTaskNode, 0, 0, 0, 0, FormatString (message, messageArgs), helpKeywordPrefix, null); BuildEngine.LogWarningEvent (bwea); } public void LogWarning (string subcategory, string warningCode, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, params object[] messageArgs) { ThrowInvalidOperationIf (BuildEngine == null, "Task is attempting to log before it was initialized"); BuildWarningEventArgs bwea = new BuildWarningEventArgs ( subcategory, warningCode, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, FormatString (message, messageArgs), helpKeyword, null); BuildEngine.LogWarningEvent (bwea); } public void LogWarningFromException (Exception exception) { LogWarningFromException (exception, false); } public void LogWarningFromException (Exception exception, bool showStackTrace) { StringBuilder sb = new StringBuilder (); sb.Append (exception.Message); if (showStackTrace) sb.Append (exception.StackTrace); LogWarning (null, null, null, null, 0, 0, 0, 0, sb.ToString (), null); } public void LogWarningFromResources (string messageResourceName, params object[] messageArgs) { if (messageResourceName == null) throw new ArgumentNullException ("messageResourceName"); LogWarningFromResources (null, null, null, null, 0, 0, 0, 0, messageResourceName, messageArgs); } public void LogWarningFromResources (string subcategoryResourceName, string warningCode, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string messageResourceName, params object[] messageArgs) { if (messageResourceName == null) throw new ArgumentNullException ("messageResourceName"); string subcategory = null; if (!String.IsNullOrEmpty (subcategoryResourceName)) subcategory = taskResources.GetString (subcategoryResourceName); LogWarning (subcategory, warningCode, helpKeyword, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, FormatResourceString (messageResourceName, messageArgs)); } public void LogWarningWithCodeFromResources (string messageResourceName, params object[] messageArgs) { // FIXME: what's different from normal logwarning? LogWarningFromResources (messageResourceName, messageArgs); } public void LogWarningWithCodeFromResources (string subcategoryResourceName, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string messageResourceName, params object[] messageArgs) { LogWarningFromResources (subcategoryResourceName, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, messageResourceName, messageArgs); } [MonoTODO] public void LogExternalProjectFinished (string message, string helpKeyword, string projectFile, bool succeeded) { } [MonoTODO] public void LogExternalProjectStarted (string message, string helpKeyword, string projectFile, string targetNames) { } void ThrowInvalidOperationIf (bool condition, string message) { if (condition) throw new InvalidOperationException (message); } protected IBuildEngine BuildEngine { get { return taskInstance?.BuildEngine; } } public bool HasLoggedErrors { get { return hasLoggedErrors; } } public string HelpKeywordPrefix { get { return helpKeywordPrefix; } set { helpKeywordPrefix = value; } } protected string TaskName { get { return taskName; } } public ResourceManager TaskResources { get { return taskResources; } set { taskResources = value; } } } }
29.40795
104
0.710393
[ "Apache-2.0" ]
radovanovic/monobsd
mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/TaskLoggingHelper.cs
14,057
C#
/******************************************************************************/ /* Project - Unity CJ Lib https://github.com/TheAllenChou/unity-cj-lib Author - Ming-Lun "Allen" Chou Web - http://AllenChou.net Twitter - @TheAllenChou Numeric Springs Intro - http://allenchou.net/2015/04/game-math-precise-control-over-numeric-springing/ Examples - http://allenchou.net/2015/04/game-math-numeric-springing-examples/ More Info - http://allenchou.net/2015/04/game-math-more-on-numeric-springing/ */ /******************************************************************************/ using System.Runtime.InteropServices; using UnityEngine; namespace CjLib { [StructLayout(LayoutKind.Sequential, Pack = 0)] public struct FloatSpring { public static readonly int Stride = 2 * sizeof(float); public float Value; public float Velocity; public void Reset() { Value = 0.0f; Velocity = 0.0f; } public void Reset(float initValue) { Value = initValue; Velocity = 0.0f; } public void Reset(float initValue, float initVelocity) { Value = initValue; Velocity = initVelocity; } public float TrackDampingRatio(float targetValue, float angularFrequency, float dampingRatio, float deltaTime) { if (angularFrequency < MathUtil.Epsilon) { Velocity = 0.0f; return Value; } float delta = targetValue - Value; float f = 1.0f + 2.0f * deltaTime * dampingRatio * angularFrequency; float oo = angularFrequency * angularFrequency; float hoo = deltaTime * oo; float hhoo = deltaTime * hoo; float detInv = 1.0f / (f + hhoo); float detX = f * Value + deltaTime * Velocity + hhoo * targetValue; float detV = Velocity + hoo * delta; Velocity = detV * detInv; Value = detX * detInv; if (Velocity < MathUtil.Epsilon && delta < MathUtil.Epsilon) { Velocity = 0.0f; Value = targetValue; } return Value; } public float TrackHalfLife(float targetValue, float frequencyHz, float halfLife, float deltaTime) { if (halfLife < MathUtil.Epsilon) { Velocity = 0.0f; Value = targetValue; return Value; } float angularFrequency = frequencyHz * MathUtil.TwoPi; float dampingRatio = 0.6931472f / (angularFrequency * halfLife); return TrackDampingRatio(targetValue, angularFrequency, dampingRatio, deltaTime); } public float TrackExponential(float targetValue, float halfLife, float deltaTime) { if (halfLife < MathUtil.Epsilon) { Velocity = 0.0f; Value = targetValue; return Value; } float angularFrequency = 0.6931472f / halfLife; float dampingRatio = 1.0f; return TrackDampingRatio(targetValue, angularFrequency, dampingRatio, deltaTime); } } [StructLayout(LayoutKind.Sequential, Pack = 0)] public struct Vector2Spring { public static readonly int Stride = 4 * sizeof(float); public Vector2 Value; public Vector2 Velocity; public void Reset() { Value = Vector2.zero; Velocity = Vector2.zero; } public void Reset(Vector2 initValue) { Value = initValue; Velocity = Vector2.zero; } public void Reset(Vector2 initValue, Vector2 initVelocity) { Value = initValue; Velocity = initVelocity; } public Vector2 TrackDampingRatio(Vector2 targetValue, float angularFrequency, float dampingRatio, float deltaTime) { if (angularFrequency < MathUtil.Epsilon) { Velocity = Vector2.zero; return Value; } Vector2 delta = targetValue - Value; float f = 1.0f + 2.0f * deltaTime * dampingRatio * angularFrequency; float oo = angularFrequency * angularFrequency; float hoo = deltaTime * oo; float hhoo = deltaTime * hoo; float detInv = 1.0f / (f + hhoo); Vector2 detX = f * Value + deltaTime * Velocity + hhoo * targetValue; Vector2 detV = Velocity + hoo * delta; Velocity = detV * detInv; Value = detX * detInv; if (Velocity.magnitude < MathUtil.Epsilon && delta.magnitude < MathUtil.Epsilon) { Velocity = Vector2.zero; Value = targetValue; } return Value; } public Vector2 TrackHalfLife(Vector2 targetValue, float frequencyHz, float halfLife, float deltaTime) { if (halfLife < MathUtil.Epsilon) { Velocity = Vector2.zero; Value = targetValue; return Value; } float angularFrequency = frequencyHz * MathUtil.TwoPi; float dampingRatio = 0.6931472f / (angularFrequency * halfLife); return TrackDampingRatio(targetValue, angularFrequency, dampingRatio, deltaTime); } public Vector2 TrackExponential(Vector2 targetValue, float halfLife, float deltaTime) { if (halfLife < MathUtil.Epsilon) { Velocity = Vector2.zero; Value = targetValue; return Value; } float angularFrequency = 0.6931472f / halfLife; float dampingRatio = 1.0f; return TrackDampingRatio(targetValue, angularFrequency, dampingRatio, deltaTime); } } [StructLayout(LayoutKind.Sequential, Pack = 0)] public struct Vector3Spring { public static readonly int Stride = 8 * sizeof(float); public Vector3 Value; private float m_padding0; public Vector3 Velocity; private float m_padding1; public void Reset() { Value = Vector3.zero; Velocity = Vector3.zero; } public void Reset(Vector3 initValue) { Value = initValue; Velocity = Vector3.zero; } public void Reset(Vector3 initValue, Vector3 initVelocity) { Value = initValue; Velocity = initVelocity; } public Vector3 TrackDampingRatio(Vector3 targetValue, float angularFrequency, float dampingRatio, float deltaTime) { if (angularFrequency < MathUtil.Epsilon) { Velocity = Vector3.zero; return Value; } Vector3 delta = targetValue - Value; float f = 1.0f + 2.0f * deltaTime * dampingRatio * angularFrequency; float oo = angularFrequency * angularFrequency; float hoo = deltaTime * oo; float hhoo = deltaTime * hoo; float detInv = 1.0f / (f + hhoo); Vector3 detX = f * Value + deltaTime * Velocity + hhoo * targetValue; Vector3 detV = Velocity + hoo * delta; Velocity = detV * detInv; Value = detX * detInv; if (Velocity.magnitude < MathUtil.Epsilon && delta.magnitude < MathUtil.Epsilon) { Velocity = Vector3.zero; Value = targetValue; } return Value; } public Vector3 TrackHalfLife(Vector3 targetValue, float frequencyHz, float halfLife, float deltaTime) { if (halfLife < MathUtil.Epsilon) { Velocity = Vector3.zero; Value = targetValue; return Value; } float angularFrequency = frequencyHz * MathUtil.TwoPi; float dampingRatio = 0.6931472f / (angularFrequency * halfLife); return TrackDampingRatio(targetValue, angularFrequency, dampingRatio, deltaTime); } public Vector3 TrackExponential(Vector3 targetValue, float halfLife, float deltaTime) { if (halfLife < MathUtil.Epsilon) { Velocity = Vector3.zero; Value = targetValue; return Value; } float angularFrequency = 0.6931472f / halfLife; float dampingRatio = 1.0f; return TrackDampingRatio(targetValue, angularFrequency, dampingRatio, deltaTime); } } [StructLayout(LayoutKind.Sequential, Pack = 0)] public struct Vector4Spring { public static readonly int Stride = 8 * sizeof(float); public Vector4 Value; public Vector4 Velocity; public void Reset() { Value = Vector4.zero; Velocity = Vector4.zero; } public void Reset(Vector4 initValue) { Value = initValue; Velocity = Vector4.zero; } public void Reset(Vector4 initValue, Vector4 initVelocity) { Value = initValue; Velocity = initVelocity; } public Vector4 TrackDampingRatio(Vector4 targetValue, float angularFrequency, float dampingRatio, float deltaTime) { if (angularFrequency < MathUtil.Epsilon) { Velocity = Vector4.zero; return Value; } Vector4 delta = targetValue - Value; float f = 1.0f + 2.0f * deltaTime * dampingRatio * angularFrequency; float oo = angularFrequency * angularFrequency; float hoo = deltaTime * oo; float hhoo = deltaTime * hoo; float detInv = 1.0f / (f + hhoo); Vector4 detX = f * Value + deltaTime * Velocity + hhoo * targetValue; Vector4 detV = Velocity + hoo * delta; Velocity = detV * detInv; Value = detX * detInv; if (Velocity.magnitude < MathUtil.Epsilon && delta.magnitude < MathUtil.Epsilon) { Velocity = Vector4.zero; Value = targetValue; } return Value; } public Vector4 TrackHalfLife(Vector4 targetValue, float frequencyHz, float halfLife, float deltaTime) { if (halfLife < MathUtil.Epsilon) { Velocity = Vector4.zero; Value = targetValue; return Value; } float angularFrequency = frequencyHz * MathUtil.TwoPi; float dampingRatio = 0.6931472f / (angularFrequency * halfLife); return TrackDampingRatio(targetValue, angularFrequency, dampingRatio, deltaTime); } public Vector4 TrackExponential(Vector4 targetValue, float halfLife, float deltaTime) { if (halfLife < MathUtil.Epsilon) { Velocity = Vector4.zero; Value = targetValue; return Value; } float angularFrequency = 0.6931472f / halfLife; float dampingRatio = 1.0f; return TrackDampingRatio(targetValue, angularFrequency, dampingRatio, deltaTime); } } [StructLayout(LayoutKind.Sequential, Pack = 0)] public struct QuaternionSpring { public static readonly int Stride = 8 * sizeof(float); public Vector4 ValueVec; public Vector4 VelocityVec; public Quaternion ValueQuat { get { return QuaternionUtil.FromVector4(ValueVec); } set { ValueVec = QuaternionUtil.ToVector4(value); } } public Quaternion VelocityQuat { get { return QuaternionUtil.FromVector4(VelocityVec, false); } set { VelocityVec = QuaternionUtil.ToVector4(value); } } public void Reset() { ValueVec = QuaternionUtil.ToVector4(Quaternion.identity); VelocityVec = Vector4.zero; } public void Reset(Vector4 initValue) { ValueVec = initValue; VelocityVec = Vector4.zero; } public void Reset(Vector4 initValue, Vector4 initVelocity) { ValueVec = initValue; VelocityVec = initVelocity; } public void Reset(Quaternion initValue) { ValueVec = QuaternionUtil.ToVector4(initValue); VelocityVec = Vector4.zero; } public void Reset(Quaternion initValue, Quaternion initVelocity) { ValueVec = QuaternionUtil.ToVector4(initValue); VelocityVec = QuaternionUtil.ToVector4(initVelocity); } public Quaternion TrackDampingRatio(Quaternion targetValue, float angularFrequency, float dampingRatio, float deltaTime) { if (angularFrequency < MathUtil.Epsilon) { VelocityVec = QuaternionUtil.ToVector4(Quaternion.identity); return QuaternionUtil.FromVector4(ValueVec); } Vector4 targetValueVec = QuaternionUtil.ToVector4(targetValue); // keep in same hemisphere for shorter track delta if (Vector4.Dot(ValueVec, targetValueVec) < 0.0f) { targetValueVec = -targetValueVec; } Vector4 delta = targetValueVec - ValueVec; float f = 1.0f + 2.0f * deltaTime * dampingRatio * angularFrequency; float oo = angularFrequency * angularFrequency; float hoo = deltaTime * oo; float hhoo = deltaTime * hoo; float detInv = 1.0f / (f + hhoo); Vector4 detX = f * ValueVec + deltaTime * VelocityVec + hhoo * targetValueVec; Vector4 detV = VelocityVec + hoo * delta; VelocityVec = detV * detInv; ValueVec = detX * detInv; if (VelocityVec.magnitude < MathUtil.Epsilon && delta.magnitude < MathUtil.Epsilon) { VelocityVec = QuaternionUtil.ToVector4(Quaternion.identity);; ValueVec = targetValueVec; } return QuaternionUtil.FromVector4(ValueVec); } public Quaternion TrackHalfLife(Quaternion targetValue, float frequencyHz, float halfLife, float deltaTime) { if (halfLife < MathUtil.Epsilon) { VelocityVec = QuaternionUtil.ToVector4(Quaternion.identity); ValueVec = QuaternionUtil.ToVector4(targetValue); return targetValue; } float angularFrequency = frequencyHz * MathUtil.TwoPi; float dampingRatio = 0.6931472f / (angularFrequency * halfLife); return TrackDampingRatio(targetValue, angularFrequency, dampingRatio, deltaTime); } public Quaternion TrackExponential(Quaternion targetValue, float halfLife, float deltaTime) { if (halfLife < MathUtil.Epsilon) { VelocityVec = QuaternionUtil.ToVector4(Quaternion.identity); ValueVec = QuaternionUtil.ToVector4(targetValue); return targetValue; } float angularFrequency = 0.6931472f / halfLife; float dampingRatio = 1.0f; return TrackDampingRatio(targetValue, angularFrequency, dampingRatio, deltaTime); } } }
28.168724
124
0.640979
[ "MIT" ]
SuomiKP31/Project-Impetus
Assets/CjLib/Script/Math/NumericSpring.cs
13,692
C#
using CleanArchWeb.Application.TodoLists.Queries.GetTodos; using CleanArchWeb.Domain.Entities; using CleanArchWeb.Domain.ValueObjects; using FluentAssertions; using NUnit.Framework; using System.Linq; using System.Threading.Tasks; namespace CleanArchWeb.Application.IntegrationTests.TodoLists.Queries { using static Testing; public class GetTodosTests : TestBase { [Test] public async Task ShouldReturnPriorityLevels() { var query = new GetTodosQuery(); var result = await SendAsync(query); result.PriorityLevels.Should().NotBeEmpty(); } [Test] public async Task ShouldReturnAllListsAndItems() { await AddAsync(new TodoList { Title = "Shopping", Colour = Colour.Blue, Items = { new TodoItem { Title = "Apples", Done = true }, new TodoItem { Title = "Milk", Done = true }, new TodoItem { Title = "Bread", Done = true }, new TodoItem { Title = "Toilet paper" }, new TodoItem { Title = "Pasta" }, new TodoItem { Title = "Tissues" }, new TodoItem { Title = "Tuna" } } }); var query = new GetTodosQuery(); var result = await SendAsync(query); result.Lists.Should().HaveCount(1); result.Lists.First().Items.Should().HaveCount(7); } } }
30.09434
71
0.529154
[ "MIT" ]
kkoziarski/dotnet-angular-identity-single-app-starter
tests/Application.IntegrationTests/TodoLists/Queries/GetTodosTests.cs
1,597
C#
namespace Microsoft.ApplicationInsights.DataContracts { using System.Collections.Generic; /// <summary> /// Represents an object that supports application-defined metrics. /// </summary> public interface ISupportMetrics { /// <summary> /// Gets a dictionary of application-defined metric names and values providing additional information about telemetry. /// </summary> IDictionary<string, double> Metrics { get; } } }
30.0625
126
0.673597
[ "MIT" ]
304NotModified/ApplicationInsights-dotnet
BASE/src/Microsoft.ApplicationInsights/DataContracts/ISupportMetrics.cs
483
C#
 namespace DrumbleApp.Shared.Enums { public enum ApplicationSetting { AllowLocation = 0, UseMetric = 3, ShowWeather = 5, StoreLocation = 6, UseUber = 7, AutoPopulateLocation = 8, AutoPopulateMostRecent = 9, AutoPopulateMostFrequent = 10, StoreRecent = 11, SkipTripSelection = 12, ShowAnnouncementsApplicationBar = 13, ShowTripApplicationBar = 14, LoginUber = 15 } }
23
45
0.592133
[ "MIT" ]
CodeObsessed/drumbleapp
DrumbleApp.Shared/Enums/ApplicationSetting.cs
485
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("RadSecClient")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RadSecClient")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("946e669b-d55f-43ad-890a-7bbcf3f1f8f6")] // 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("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
37.621622
84
0.747845
[ "MIT" ]
vforteli/RadSec-Client
Properties/AssemblyInfo.cs
1,395
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: EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type AndroidForWorkVpnConfigurationRequest. /// </summary> public partial class AndroidForWorkVpnConfigurationRequest : BaseRequest, IAndroidForWorkVpnConfigurationRequest { /// <summary> /// Constructs a new AndroidForWorkVpnConfigurationRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public AndroidForWorkVpnConfigurationRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified AndroidForWorkVpnConfiguration using POST. /// </summary> /// <param name="androidForWorkVpnConfigurationToCreate">The AndroidForWorkVpnConfiguration to create.</param> /// <returns>The created AndroidForWorkVpnConfiguration.</returns> public System.Threading.Tasks.Task<AndroidForWorkVpnConfiguration> CreateAsync(AndroidForWorkVpnConfiguration androidForWorkVpnConfigurationToCreate) { return this.CreateAsync(androidForWorkVpnConfigurationToCreate, CancellationToken.None); } /// <summary> /// Creates the specified AndroidForWorkVpnConfiguration using POST. /// </summary> /// <param name="androidForWorkVpnConfigurationToCreate">The AndroidForWorkVpnConfiguration to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created AndroidForWorkVpnConfiguration.</returns> public async System.Threading.Tasks.Task<AndroidForWorkVpnConfiguration> CreateAsync(AndroidForWorkVpnConfiguration androidForWorkVpnConfigurationToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<AndroidForWorkVpnConfiguration>(androidForWorkVpnConfigurationToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified AndroidForWorkVpnConfiguration. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified AndroidForWorkVpnConfiguration. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<AndroidForWorkVpnConfiguration>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified AndroidForWorkVpnConfiguration. /// </summary> /// <returns>The AndroidForWorkVpnConfiguration.</returns> public System.Threading.Tasks.Task<AndroidForWorkVpnConfiguration> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified AndroidForWorkVpnConfiguration. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The AndroidForWorkVpnConfiguration.</returns> public async System.Threading.Tasks.Task<AndroidForWorkVpnConfiguration> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<AndroidForWorkVpnConfiguration>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified AndroidForWorkVpnConfiguration using PATCH. /// </summary> /// <param name="androidForWorkVpnConfigurationToUpdate">The AndroidForWorkVpnConfiguration to update.</param> /// <returns>The updated AndroidForWorkVpnConfiguration.</returns> public System.Threading.Tasks.Task<AndroidForWorkVpnConfiguration> UpdateAsync(AndroidForWorkVpnConfiguration androidForWorkVpnConfigurationToUpdate) { return this.UpdateAsync(androidForWorkVpnConfigurationToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified AndroidForWorkVpnConfiguration using PATCH. /// </summary> /// <param name="androidForWorkVpnConfigurationToUpdate">The AndroidForWorkVpnConfiguration to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The updated AndroidForWorkVpnConfiguration.</returns> public async System.Threading.Tasks.Task<AndroidForWorkVpnConfiguration> UpdateAsync(AndroidForWorkVpnConfiguration androidForWorkVpnConfigurationToUpdate, CancellationToken cancellationToken) { if (androidForWorkVpnConfigurationToUpdate.AdditionalData != null) { if (androidForWorkVpnConfigurationToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.ResponseHeaders) || androidForWorkVpnConfigurationToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.StatusCode)) { throw new ClientException( new Error { Code = GeneratedErrorConstants.Codes.NotAllowed, Message = String.Format(GeneratedErrorConstants.Messages.ResponseObjectUsedForUpdate, androidForWorkVpnConfigurationToUpdate.GetType().Name) }); } } if (androidForWorkVpnConfigurationToUpdate.AdditionalData != null) { if (androidForWorkVpnConfigurationToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.ResponseHeaders) || androidForWorkVpnConfigurationToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.StatusCode)) { throw new ClientException( new Error { Code = GeneratedErrorConstants.Codes.NotAllowed, Message = String.Format(GeneratedErrorConstants.Messages.ResponseObjectUsedForUpdate, androidForWorkVpnConfigurationToUpdate.GetType().Name) }); } } this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<AndroidForWorkVpnConfiguration>(androidForWorkVpnConfigurationToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IAndroidForWorkVpnConfigurationRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IAndroidForWorkVpnConfigurationRequest Expand(Expression<Func<AndroidForWorkVpnConfiguration, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IAndroidForWorkVpnConfigurationRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IAndroidForWorkVpnConfigurationRequest Select(Expression<Func<AndroidForWorkVpnConfiguration, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="androidForWorkVpnConfigurationToInitialize">The <see cref="AndroidForWorkVpnConfiguration"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(AndroidForWorkVpnConfiguration androidForWorkVpnConfigurationToInitialize) { } } }
47.738397
200
0.651759
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/AndroidForWorkVpnConfigurationRequest.cs
11,314
C#
using FluentValidation; using Microsoft.EntityFrameworkCore; using SW.Mtm.Domain; using SW.Mtm.Model; using SW.PrimitiveTypes; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.ExceptionServices; using System.Text; using System.Threading.Tasks; namespace SW.Mtm.Resources.Accounts { [Protect(RequireRole = true)] [HandlerName("resetpassword")] class ResetPassword : ICommandHandler<string, AccountResetPassword> { private readonly MtmDbContext dbContext; public ResetPassword(MtmDbContext dbContext) { this.dbContext = dbContext; } async public Task<object> Handle(string accountIdOrEmail, AccountResetPassword request) { var account = await dbContext.FindAsync<Account>(accountIdOrEmail); if (account == null) account = await dbContext.Set<Account>().Where(i => i.Email == accountIdOrEmail).SingleOrDefaultAsync(); if (account == null) throw new SWNotFoundException(accountIdOrEmail); if (account.EmailProvider != EmailProvider.None) throw new SWValidationException("EmailProvider", "Not allowed for external email providers."); if ((account.LoginMethods & LoginMethod.EmailAndPassword) != LoginMethod.EmailAndPassword) throw new SWValidationException("LoginMethod", "Invalid login method."); var token = await dbContext.FindAsync<PasswordResetToken>(request.Token); if (token == null) throw new SWUnauthorizedException(); account.SetPassword(SecurePasswordHasher.Hash(request.NewPassword)); dbContext.Remove(token); await dbContext.SaveChangesAsync(); return null; } class Validate : AbstractValidator<AccountResetPassword> { public Validate() { RuleFor(i => i.Token).NotEmpty(); RuleFor(i => i.NewPassword).NotEmpty(); } } } }
30.985075
120
0.643545
[ "MIT" ]
simplify9/Mtm
SW.Mtm.Api/Resources/Accounts/ResetPassword.cs
2,078
C#
namespace LeetCode.Naive.Problems; /// <summary> /// Problem: https://leetcode.com/problems/concatenation-of-array/ /// Submission: https://leetcode.com/submissions/detail/525480252/ /// </summary> internal class P1929 { public class Solution { public int[] GetConcatenation(int[] nums) { return new[] { nums, nums }.SelectMany(_ => _).ToArray(); } } }
23.529412
70
0.63
[ "MIT" ]
viacheslave/algo
leetcode/c#/Problems/P1929.cs
400
C#
using System; namespace NBitcoin.BouncyCastle.Crypto { /// <remarks>Block cipher engines are expected to conform to this interface.</remarks> public interface IBufferedCipher { /// <summary>The name of the algorithm this cipher implements.</summary> string AlgorithmName { get; } /// <summary>Initialise the cipher.</summary> /// <param name="forEncryption">If true the cipher is initialised for encryption, /// if false for decryption.</param> /// <param name="parameters">The key and other data required by the cipher.</param> void Init(bool forEncryption, ICipherParameters parameters); int GetBlockSize(); int GetOutputSize(int inputLen); int GetUpdateOutputSize(int inputLen); byte[] ProcessByte(byte input); int ProcessByte(byte input, byte[] output, int outOff); byte[] ProcessBytes(byte[] input); byte[] ProcessBytes(byte[] input, int inOff, int length); int ProcessBytes(byte[] input, byte[] output, int outOff); int ProcessBytes(byte[] input, int inOff, int length, byte[] output, int outOff); byte[] DoFinal(); byte[] DoFinal(byte[] input); byte[] DoFinal(byte[] input, int inOff, int length); int DoFinal(byte[] output, int outOff); int DoFinal(byte[] input, byte[] output, int outOff); int DoFinal(byte[] input, int inOff, int length, byte[] output, int outOff); /// <summary> /// Reset the cipher. After resetting the cipher is in the same state /// as it was after the last init (if there was one). /// </summary> void Reset(); } }
35.088889
88
0.675744
[ "MIT" ]
dthorpe/NBitcoin
NBitcoin.BouncyCastle/crypto/IBufferedCipher.cs
1,579
C#