public void Build(ScriptInfo script) { using (TextReader reader = new StringReader(script.Code)) { string line; while ((line = reader.ReadLine()) != null) { MatchCollection matches = _regex.Matches(line); if (matches.Count == 1) { Match match = matches[0]; string family = match.Groups["family"].Value; string name = match.Groups["name"].Value; BuildDependency(script, family, name); } else { while (line == "|") { line = reader.ReadLine(); } break; } } script.Code = string.Format("{1}{0}{2}{0}", Environment.NewLine, line, reader.ReadToEnd()); } }
public string GetScript(string name, ProxyScriptType type) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException("name is null or empty!", "name"); } var cacheKey = type + "_" + name; lock (CachedScripts) { var cachedScript = CachedScripts.GetOrDefault(cacheKey); if (cachedScript == null) { var dynamicController = DynamicApiControllerManager.GetAll().FirstOrDefault(ci => ci.ServiceName == name); if (dynamicController == null) { throw new HttpException(404, "There is no such a service: " + cacheKey); } var script = CreateProxyGenerator(type, dynamicController, true).Generate(); CachedScripts[cacheKey] = cachedScript = new ScriptInfo(script); } return cachedScript.Script; } }
public static string GetScript(string name) { if (string.IsNullOrWhiteSpace(name) || !name.Contains("/")) { throw new ArgumentException("name must be formatted as {areaName}/{serviceName}", "name"); } lock (Scripts) { //TODO: Use reader writer lock for performance reasons if (Scripts.ContainsKey(name)) { return Scripts[name].Script; } var controllerInfo = DynamicApiControllerManager.Find(name.ToPascalCase()); if (controllerInfo == null) { throw new HttpException(404, "There is no such a service: " + name); } var script = new ControllerScriptProxyGenerator().GenerateFor(controllerInfo); Scripts[name] = new ScriptInfo(name, script); return script; } }
/// <summary> /// Create a new test batch /// </summary> /// <param name="name">Name of the test batch</param> /// <param name="description">Description of the test batch</param> /// <param name="tests">Array containing all of the tests to add to the batch</param> /// <returns></returns> public Boolean CreateBatch(String name, String description, ScriptInfo[] tests) { //set the batch's properties Batch temp = new Batch(); temp.name = name; temp.description = description; temp.scripts = tests; bool result; //create the batch try { result= Connection.Servicer.makeBatch(temp); } catch (System.Net.WebException e) { error = e.Message; error_type = MessageBoxIcon.Error; return false; } //batch creation failed if (!result) { error = "An error occured while creating the batch. Please try again."; error_type = MessageBoxIcon.Error; return false; } return true; }
/// <summary> /// Performs PHP inclusion on a specified script. Equivalent to <see cref="PHP.Core.ScriptContext.IncludeScript"/>. /// </summary> /// <param name="relativeSourcePath"> /// Path to the target script source file relative to the web application root. /// </param> /// <param name="script"> /// Script info (i.e. type called <c>Default</c> representing the target script) or any type from /// the assembly where the target script is contained. In the latter case, the script type is searched in the /// assembly using value of <paramref name="relativeSourcePath"/>. /// </param> /// <returns>The value returned by the global code of the target script.</returns> /// <exception cref="InvalidOperationException">Request context has been disposed.</exception> /// <exception cref="ArgumentNullException"><paramref name="relativeSourcePath"/> or <paramref name="script"/> are <B>null</B> references.</exception> /// <exception cref="ArgumentException">Script type cannot be resolved.</exception> /// <exception cref="InvalidScriptAssemblyException">The target assembly is not a valid Phalanger compiled assembly.</exception> public object IncludeScript(string/*!*/ relativeSourcePath, ScriptInfo/*!*/ script) { if (disposed) throw new InvalidOperationException(CoreResources.GetString("instance_disposed")); return scriptContext.IncludeScript(relativeSourcePath, script); }
/// <summary> /// Gets the component. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static ITibiaAction GetAction(Type type, TibiaClient client, ScriptInfo script) { if (Container == null) { InitializeContainer(); } var res = (ITibiaAction)Container.Resolve(type); res.Client = client; res.Script = script; return res; }
public void ScriptInfoConstructor_Test() { string url = "Foo"; string localPath = "Foo"; string cdnPath = "Foo"; ScriptType scriptType = new ScriptType(); bool siteWide = false; string area = "Foo"; ScriptInfo target = new ScriptInfo(url, localPath, scriptType, area); }
public void ScriptInfoConstructor_Source_Test() { string source = "Foo"; string cdnPath = "Foo"; ScriptType scriptType = new ScriptType(); bool siteWide = false; string area = "Foo"; string key = "123"; ScriptInfo target = new ScriptInfo(source, scriptType, key, area); }
public void ScriptFileList_Add_ScriptInfo_Increases_Collection_Count() { ScriptFileList target = new ScriptFileList(); ScriptInfo info = new ScriptInfo("", "", ScriptType.JavaScript); target.Add(info); int expected = 1; int actual = target.Scripts.Count(); Assert.AreEqual(expected, actual); }
public void ScriptFileList_Add_StyleSheet_ScriptInfo_Is_Added_To_Collection() { ScriptFileList target = new ScriptFileList(); ScriptInfo info = new ScriptInfo("", "", ScriptType.Stylesheet); target.Add(info); bool contains = target.Scripts.Contains(info); Assert.IsTrue(contains); }
void IActiveScriptSite.GetItemInfo(string name, ScriptInfo returnMask, out IntPtr item, IntPtr typeInfo) { if ((returnMask & ScriptInfo.ITypeInfo) == ScriptInfo.ITypeInfo) throw new NotImplementedException(); object value; if (!_namedItems.TryGetValue(name, out value)) throw new COMException(null, TYPE_E_ELEMENTNOTFOUND); item = Marshal.GetIUnknownForObject(value); }
public static MvcHtmlString AddScriptSource(this HtmlHelper helper, Func<dynamic, HelperResult> source, string key, string area = null) { var scriptType = ScriptType.JavaScript; var info = new ScriptInfo(source(null).ToHtmlString(), scriptType, key, area); var manager = new ScriptManager(); manager.Add(info); return MvcHtmlString.Empty; }
public static MvcHtmlString AddJavaScript(this HtmlHelper helper, string localPath, string area = null) { var scriptType = ScriptType.JavaScript; var info = new ScriptInfo(localPath, helper.ViewContext.HttpContext.Server.MapPath(localPath).Replace(@"/", @"\"), scriptType, area); var manager = new ScriptManager(); manager.Add(info); return MvcHtmlString.Empty; }
public void ScriptType_Test() { string url = "Foo"; string localPath = "Foo"; string cdnPath = "Foo"; ScriptType scriptType = new ScriptType(); bool siteWide = false; string area = "Foo"; ScriptInfo target = new ScriptInfo(url, localPath,scriptType, area); ScriptType expected = new ScriptType(); ScriptType actual; target.ScriptType = expected; actual = target.ScriptType; Assert.AreEqual(expected, actual); }
private static ScriptInfo ParseConfig(string text) { var si = new ScriptInfo(); var lines = text.Split(new[] {'\n', '\r'}, StringSplitOptions.RemoveEmptyEntries); var mode = ParseMode.None; var players = new List<PlayerInfo>(); int lastTeam = -1; foreach (var s in lines) { string line = s.Trim(); if (line.StartsWith("[player", StringComparison.InvariantCultureIgnoreCase)) { mode = ParseMode.Player; var m = Regex.Match(line, "\\[player([0-9]+)", RegexOptions.IgnoreCase); if (m.Success) { int id = int.Parse(m.Groups[1].Value); var pi = new PlayerInfo(id); players.Add(pi); } else throw new ApplicationException("Error parsing " + scriptName); } else if (line.StartsWith("[team", StringComparison.InvariantCultureIgnoreCase)) { mode = ParseMode.Team; var m = Regex.Match(line, "\\[team([0-9]+)", RegexOptions.IgnoreCase); if (m.Success) lastTeam = int.Parse(m.Groups[1].Value); else throw new ApplicationException("Error parsing " + scriptName); } else { var m = Regex.Match(line, "([^=]+)=([^;]+)"); if (m.Success) { string var = m.Groups[1].Value; string val = m.Groups[2].Value; if (mode == ParseMode.Player) { if (String.Compare(var, "team", true) == 0) players[players.Count - 1].Team = int.Parse(val); else if (String.Compare(var, "spectator", true) == 0) players[players.Count - 1].IsSpectator = (val == "1"); else if (String.Compare(var, "name", true) == 0) { players[players.Count - 1].Name = val; if (players[players.Count - 1].Id == 0) si.Host = val; } } else if (mode == ParseMode.Team) if (String.Compare(var, "allyteam", true) == 0) for (int i = 0; i < players.Count; ++i) if (players[i].Team == lastTeam) players[i].Ally = int.Parse(val); } } } foreach (var pi in players) { if (!pi.IsSpectator) { var pp = new ScriptInfo.PlayerPair(pi.Ally, pi.Name); si.Players.Add(pp); } } return si; }
public void GenerateScriptsIfNeeded(ProxyScriptType type) { lock (CachedScripts) { if (CachedScripts.Count > 0) { return; } var dynamicControllers = DynamicApiControllerManager.GetAll(); foreach (var dynamicController in dynamicControllers) { var proxyGenerator = CreateProxyGenerator(type, dynamicController, true); var script = proxyGenerator.Generate(); var cacheKey = type + "_" + dynamicController.ServiceName; CachedScripts[cacheKey] = new ScriptInfo(script); } } }
private void BuildDependency(ScriptInfo script, string family, string name) { string fullName = ScriptInfo.FormatPrefixedFullName("Script", family, name); if (script.IsForm || !StringUtils.CaseInsensitiveEquals(script.FullName, fullName)) { ScriptInfo dependencyScript; if (!_scripts.TryGetValue(fullName, out dependencyScript)) { Plugin plugin = Plugin.LoadByName(name, family, PluginType.ActiveScript); if (plugin == null) { LogWarning("Include script '{0}:{1}' not found", family, name); } else { dependencyScript = new ScriptInfo(plugin); Debug.Assert(!_scripts.ContainsKey(dependencyScript.PrefixedFullName)); _scripts.Add(dependencyScript.PrefixedFullName, dependencyScript); Build(dependencyScript); } } if (dependencyScript != null && !dependencyScript.IsInvalid) { Debug.Assert(_scripts.ContainsKey(dependencyScript.PrefixedFullName)); script.Dependencies[dependencyScript.PrefixedFullName] = dependencyScript; foreach (ScriptInfo item in dependencyScript.Dependencies.Values) { if (item != script && !item.IsInvalid) { Debug.Assert(_scripts.ContainsKey(item.PrefixedFullName)); script.Dependencies[item.PrefixedFullName] = item; } } } } }
public void ScriptManager_Add_External_StyleSheet_ScriptInfo_Test() { var cacheManager = new Mock<ICacheManager>(); var contextAccessor = new Mock<IHttpContextAccessor>(); var list = new Mock<IScriptFileList>(); var context = new Mock<HttpContextBase> { DefaultValue = DefaultValue.Mock }; contextAccessor.Setup(c => c.Current()).Returns(context.Object); context.SetupGet(c => c.Application["__sm__Stylesheet"]).Returns(() => list.Object); var target = new ScriptManager(cacheManager.Object, contextAccessor.Object); IScriptInfo info = new ScriptInfo(null, "SomeLocalPath", ScriptType.Stylesheet); target.Add(info); list.Verify(l => l.Add(info), Times.Once()); }
public string GetAllScript(ProxyScriptType type) { lock (CachedScripts) { var cacheKey = type + "_all"; if (!CachedScripts.ContainsKey(cacheKey)) { var script = new StringBuilder(); var dynamicControllers = DynamicApiControllerManager.GetAll(); foreach (var dynamicController in dynamicControllers) { var proxyGenerator = CreateProxyGenerator(type, dynamicController, false); script.AppendLine(proxyGenerator.Generate()); script.AppendLine(); } CachedScripts[cacheKey] = new ScriptInfo(script.ToString()); } return CachedScripts[cacheKey].Script; } }
/// <summary> /// Performs PHP inclusion on a specified script. /// </summary> /// <param name="relativeSourcePath"> /// Path to the target script source file relative to the application source root /// (see <c>Configuration.Application.Compiler.SourceRoot</c>. /// </param> /// <param name="script"> /// Script type (i.e. type called <c>Default</c> representing the target script) or any type from /// the assembly where the target script is contained (useful for multi-script assemblies, where script types are /// not directly available from C# as they have mangled names). In the latter case, the script type is searched in the /// assembly using value of <paramref name="relativeSourcePath"/>. /// </param> /// <returns>The value returned by the global code of the target script.</returns> /// <remarks> /// <para> /// The inclusion inheres in adding the target to the list of included scripts on the current script context /// (see <c>ScriptContext.Scripts</c> and in a call to the global code of the target script. /// </para> /// </remarks> /// <exception cref="InvalidOperationException">Request context has been disposed.</exception> /// <exception cref="ArgumentNullException"><paramref name="relativeSourcePath"/> or <paramref name="script"/> are <B>null</B> references.</exception> /// <exception cref="ArgumentException">Script type cannot be resolved.</exception> /// <exception cref="InvalidScriptAssemblyException">The target assembly is not a valid Phalanger compiled assembly.</exception> internal object IncludeScript(string/*!*/ relativeSourcePath, ScriptInfo/*!*/ script) { //if (type == null) // throw new ArgumentNullException("type"); if (relativeSourcePath == null) throw new ArgumentNullException("relativeSourcePath"); if (script == null) throw new ArgumentException("script"); FullPath source_root = Configuration.Application.Compiler.SourceRoot; PhpSourceFile source_file = new PhpSourceFile( new FullPath(source_root), new FullPath(Path.Combine(source_root, relativeSourcePath))); // the first script becomes the main one: if (MainScriptFile == null) DefineMainScript(script, source_file); return GuardedCall((ScriptInfo scriptInfo) => { //return PhpScript.InvokeMainHelper( // (Type)scriptType, return scriptInfo.Main( this, null, // no local variables null, // no object context null, // no class context true); }, script, true); }
/// <summary> /// Compile ok store into cache, /// Arguement sequence:IProduct,IMB, Delivery,Part,Model,Family,TestLog,BOM /// </summary> /// <param name="scriptType"></param> /// <param name="name"></param> /// <param name="code"></param> /// <param name="parameters"></param> /// <returns></returns> public static Delegate CompileWithCache(ScriptTypeEnum scriptType, string name, string code, params ParameterExpression[] parameters) { lock (syncObject) { if (ParserInfoList.ContainsKey(name)) { ScriptInfo info = ParserInfoList[name]; if (info.ScriptType == scriptType && info.Code.Equals(code)) { return info.CompileFunction; } } var lambda = Compile(scriptType, code, parameters); ParserInfoList[name] = new ScriptInfo { ScriptType = ScriptTypeEnum.Condition, Code = code, CompileFunction = lambda, }; return lambda; } }
public Sql7Scripter(ScriptInfo scriptInfo) { }
protected override void WriteScript(ScriptInfo info) { var script = info.Script; output.WriteLine("// ScriptName: {0}", script.Name); output.WriteLine("// CodeName: {0} ", script.Code.Name); output.WriteLine("// ArgumentCount: {0}", info.ArgumentCount); output.WriteLine(); WriteLocals(info); output.WriteLine(); output.Write(info.Block); output.WriteLine(); // extra next line }
public static void StopScript(ScriptInfo scriptInfo) { if (IDE.StopScriptRequested != null) { IDE.StopScriptRequested(scriptInfo, EventArgs.Empty); } }
public void CreatePlugin(string path) { try { ScriptSource script = PythonEngine.CreateScriptSourceFromFile(path); CompiledCode code = script.Compile(); ScriptInfo info = new ScriptInfo(); info.Scope = PythonEngine.CreateScope(); info.Scope.SetVariable("zchat", this); code.Execute(info.Scope); object somefunc; if (!info.Scope.TryGetVariable("info", out somefunc)) throw new Exception("No info() function found. This function must be defined and return a tuple of 4 strings (script name, version, author, description)."); object val = PythonEngine.Operations.Invoke(somefunc); PythonTuple tuple = val as PythonTuple; if (tuple == null) throw new Exception("The info() function returned a " + val.GetType().Name + " instead of a tuple of strings."); if (tuple.Count != 4) throw new Exception("The info() function returned a " + tuple.Count + "-item tuple instead of a 4-item tuple. It should return Name, Version, Author, Description."); info.Name = tuple[0] as string; if (info.Name == null) throw new Exception("The info() function did not return correct data. The first item in the returned tuple was not a string. It should be the script name."); info.Version = tuple[1] as string; if (info.Version == null) throw new Exception("The info() function did not return correct data. The second item in the returned tuple was not a string. It should be the script version."); info.Author = tuple[2] as string; if (info.Author == null) throw new Exception("The info() function did not return correct data. The third item in the returned tuple was not a string. It should be the script author."); info.Description = tuple[3] as string; if (info.Description == null) throw new Exception("The info() function did not return correct data. The fourth item in the returned tuple was not a string. It should be the script description."); LoadedScripts.Add(info); } catch (SyntaxErrorException e) { ExceptionOperations eo = PythonEngine.GetService<ExceptionOperations>(); string error = eo.FormatException(e); string caption = String.Format("Syntax error in \"{0}\"", Path.GetFileName(path)); MessageBox.Show(error, caption, MessageBoxButton.OK, MessageBoxImage.Error); } catch (Exception e) { MessageBox.Show("Error loading the " + Path.GetFileName(path) + " script." + Environment.NewLine + Environment.NewLine + e.Message, "Error loading script", MessageBoxButton.OK, MessageBoxImage.Error); } }
public CacheEntry(Type/*!*/ scriptType, ScriptAssembly/*!*/ scriptAssembly, DateTime buildTimeStamp, string[]/*!*/ includers, string[]/*!*/ includees, bool fileTimeChecked) { Debug.Assert(scriptType != null && scriptAssembly != null && includers != null); this.scriptInfo = new ScriptInfo(scriptType); this.scriptAssembly = scriptAssembly; this.buildTimeStamp = buildTimeStamp; this.includers = new List<string>(includers); this.fileTimeChecked = fileTimeChecked; this.includees = new List<string>(includees); }
internal void Bake() { scriptInfo = new ScriptInfo(ScriptTypeBuilder.CreateType(), null); //FastReflect(); }
/// <summary> /// Registers information about a script. /// </summary> /// <param name="scriptInfo">The information about a script.</param> public static void RegisterScript(ScriptInfo scriptInfo) { }
/// <summary> /// Initializes a new instance of the <see cref="ScriptActionException"/> class. /// </summary> /// <param name="script">The script.</param> /// <param name="message">The message.</param> public ScriptActionException(ScriptInfo script, string message) { this.Script = script; this.Message = message; }
/// <summary>Обработка транзакции. Если обработка транзакции завершилась успешно - возвращается true</summary> bool ProcessTransactionItem(OracleConnection Connection, RecalculationTransactionItem Item, SharedDataInfo SharedData) { // блокируем транзакцию OraQuery.Execute(Connection, "select 1 from Transactions where ID = :ID for update nowait", new string[] { "ID" }, new object[] { Item.ID }); // создаём скрипт и транзакцию, загружаем её, обрабатываем, записываем статистику var CurrentScript = new ScriptInfo(TransactionalMechanismTypes.UseConnection, SharedData, new FileLogger(""), null); if (!Item.IsCorrectSignature) CurrentScript.ErrorMessage.Add("Некорректная подпись безопасности транзакции {0}. Пересчёт остановлен", Item.ID); if (CurrentScript.ErrorMessage.IsEmpty) { try { CurrentScript.Connection = Connection; TransactionInfo CurrentTransaction = CurrentScript.Transaction, OriginalTransaction, Difference; // заполняем поля, необходимые для формирования транзакции CurrentTransaction.PurchaseID = Item.ID; CurrentTransaction.TerminalDateTime = Item.TerminalDateTime; CurrentTransaction.Terminal.ID = Item.TerminalID; CurrentTransaction.Card.Number = Item.CardNumber; CurrentTransaction.Card.Contract.ID = Item.ContractID; CurrentTransaction.AboutDevice.SerialNumber = "0"; CurrentTransaction.Flags = Item.Flags; CurrentTransaction.BehaviorFlags |= TransactionBehaviorFlags.AvoidChecks; // устанавливаем флаг игнорирования правил и проверок // у этого скрипта должна быть своя инициализация (без заполнения ID транзакции и проверки состояния терминала и карты if (CurrentScript.InitializeTerminal(false) && CurrentScript.InitializeCardFirst()) // инициализируем теримнал без проверки состояния и карту { CurrentScript.SelectCardPlugin(Item.CardScriptID); CurrentScript.Config = new ScriptConfiguration(CurrentScript); CurrentScript.Config.Load(Item.ParamSetPeriodID); // используем конфигурацию скрипта, действующую на момент транзакции CurrentScript.InitializeCardLast(false); // завершаем инициализацию карты без вызова скриптовой инциализации, т.к. карта может работать со счётчиками, которые ещё не подготовлены CurrentScript.Card.StatusID = Item.CardStatusID; // изменяем статус карты на тот, который был в момент транзакции // Изменяем дату последнего обслуживания карты на ту, когда была транзакция. LastServiceDate влияет на загрузку предыдущих значений счётчиков. CurrentScript.Card.LastServiceDate = Item.CardLastServiceDateTime; // загружаем данные по транзакции (восстанавливаем состояние окружения на момент ДО транзакции CurrentTransaction.Load(Item.ID, true); CurrentTransaction.Card.Contract.OwnerAccounts.LoadFromTransaction(Item.ID, false); CurrentTransaction.Card.Contract.Accounts.LoadFromTransaction(Item.ID, false); CurrentTransaction.Card.Counters.LoadFromTransaction(Item.ID, false); // 02/04/15 ещё можно подумать - а если в транзакции не было счётчика, а сейчас на карте есть? Может быть стОит очищать счётчики перед загрузкой из транзакции? CurrentTransaction.Card.CountersSP.LoadFromTransaction(Item.ID, false); CurrentTransaction.Contract.Counters.LoadFromTransaction(Item.ID, false); CurrentScript.CurrentCardScript.InitializeCard(); // вызываем скриптовую функцию инициализации карты var CurrentContract = CurrentScript.Card.Contract; if (Request.Type == RecalculationRequestTypes.Compensation) { if (Request.LastContract == null || Request.LastContract.ID != CurrentContract.ID) { Request.LastContract = CurrentContract; // устанавливаем текущий договор пересчёта CurrentContract.DataAccumulators = new DataAccumulatorsInfo(CurrentContract, Request); // Если пересчёт компенсационный, то разрешаем долгие процедуры } else if (Request.LastContract != null && Request.LastContract.ID == CurrentContract.ID) { CurrentContract.DataAccumulators = Request.LastContract.DataAccumulators; CurrentContract.DataAccumulators.Contract = CurrentContract; // это нужно для того, чтобы аккумулятор брал корректные значения текущей транзакции } } if (CurrentScript.ErrorMessage.IsEmpty) { CurrentTransaction.RSPackage.Calculate(); // пересчитываем чек транзакции до расчёта OriginalTransaction = CurrentTransaction.Clone(); // сохраняем эталон пакета ККМ перед расчётами OriginalTransaction.Load(Item.ID, false); // загружаем данные чека на момент ПОСЛЕ транзакции OriginalTransaction.RSPackage.Calculate(); // пересчитываем чек после загрузки if (CurrentScript.ProvideCalculateReceipt()) // вызываем функции пересчёта чека и покупки CurrentScript.ProvidePurchase(false, false); /*// Заменено 20/08/2014, т.к. только скриптовые функции не сделают всей работы // вызываем скриптовые функции расчёта и покупки if (!Script.Fiscal.Flags.HasFlag(FiscalReceiptFlags.WithoutRecalculation)) // если нет флага "БЕЗ ПЕРЕСЧЁТА" Script.CurrentCardScript.ChangeReceipt(); // делаем пересчёт чека Current.RSPackage.Calculate(); // пересчитываем чек после расчёта Script.CurrentCardScript.Purchase(); // проводим покупку */ // в Current сохраняем неизменной пересчитанную транзакцию if (CurrentScript.ErrorMessage.IsEmpty && Request.Type == RecalculationRequestTypes.Compensation) // при компенсационном пересчёте добавляем текущую транзакцию в накопление { // выбираем все градации с периодами "текущий пересчёт", используемые договором var ContractGraduations = CurrentContract.GetGraduationsForPeriod(GraduationPeriods.CurrentRecalculationPeriod); foreach (var Graduation in ContractGraduations) { // проверяем, можно ли текущую транзакцию добавлять в накопитель градации var RestrictionData = OraQuery.Execute(Connection, "select opsOnlineRestrictions.CheckGraduation(:GraduationID, :TerminalID, null, null, null, null, :ContractID, null, null, null) from dual", new string[] { "GraduationID", "TerminalID", "ContractID" }, new object[] { Graduation.ID, CurrentTransaction.Terminal.ID, CurrentContract.ID }); if (Cvt.ToInt32(RestrictionData[0, 0]) != 0) { var Accumulator = CurrentContract.DataAccumulators.GetAccumulator(Graduation.ID); // накопитель текущего пересчёта (для плавного изменения скидки) if (Accumulator != null) { var TransactionAccumulator = new DataAccumulatorInfo(CurrentContract.DataAccumulators, Graduation); // создаём транзакционный накопитель для текушей градации TransactionAccumulator.LoadFromCurrentTransaction(); // загружаем данные текущей транзакции в накопитель Accumulator.Add(TransactionAccumulator); // добавляем к накопителю текущего пересчёта, накопитель текущей транзакции } } } } Difference = CurrentTransaction.Clone(); if (CurrentScript.ErrorMessage.IsEmpty) { // рассчитываем разницу Difference.RSPackage = RSPackageInfo.Substract(Difference, CurrentTransaction.RSPackage, OriginalTransaction.RSPackage); // вычитаем пересчитанный пакет транзакции из оригинального Difference.Card.Counters.CompareWithTransaction(Item.ID); // в difference лежат изменения относительно текущей транзакции Difference.Card.CountersSP.CompareWithTransaction(Item.ID, Difference.Terminal.ServicePoint.ID); // в difference нас интересуют ТОЛЬКО ИЗМЕНЕНИЯ счётчиков и счетов. Всё остальныое - игнорируем Difference.Contract.Counters.CompareWithTransaction(Item.ID); // в difference лежат изменения относительно текущей транзакции Difference.Contract.Accounts.CompareWithTransaction(Item.ID); Difference.Contract.OwnerAccounts.CompareWithTransaction(Item.ID); } // определяем есть ли что сохранять... if (CurrentScript.ErrorMessage.IsEmpty && !Difference.IsZero) { // known issue: if only messages was changed they will not be updated. Data change is strongly required (is necessarily) // Сохраняем изменения транзакции Log.Message("Сохранение изменённой транзакции " + CurrentTransaction.PurchaseID); if (CurrentTransaction.Update()) // обновляем пересчитанную транзакцию { // перед сохранением разницы устанавливаем причину (не транзакция, а пересчёт транзакции) Difference.Contract.Counters.Reason = ChangeReasons.Recalculation; Difference.Contract.Accounts.Reason = ChangeReasons.Recalculation; Difference.Contract.OwnerAccounts.Reason = ChangeReasons.Recalculation; Difference.Card.Counters.Reason = ChangeReasons.Recalculation; Difference.Card.CountersSP.Reason = ChangeReasons.Recalculation; Difference.Card.Save(true); // изменяем значения счётчиков и счетов договора на величину разницы между текущей транзакцией и оригинальной Item.IsChanged = true; } } } } } catch (Exception e) { CurrentScript.ErrorMessage.Add("Неизвестная ошибка: {0}", e.Message); Log.Message("Recalculator.ProcessTransactionItem(): {0}\n{1}", e.Message, e.StackTrace); } finally { if (CurrentScript.ErrorMessage.IsEmpty) { CurrentScript.SetReadyForCommit(); CurrentScript.ProvideCommit(); } else { Log.Message("Ошибка при обработке транзакции {0}\n{1}", Item.ID, CurrentScript.ErrorMessage.ToString()); Item.ErrorMessage = CurrentScript.ErrorMessage.ToString(); CurrentScript.Rollback(); } CurrentScript.ReleaseResources(); } } return CurrentScript.ErrorMessage.IsEmpty; }
/// <summary> /// Интерфейсная функция первоначальной инициализации скрипта /// </summary> public bool InitializeScript(ScriptInfo Script) { this.Script = Script; return ErrorMessage.IsEmpty; }