public ParameterCollection CheckParameters(string[] parameters) { ParameterCollection parameterCollection = new ParameterCollection(); switch (parameters.Length) { case 0: parameterCollection.Add("prompt"); return parameterCollection; case 2: int difficultyInt; if (parameters[0].StartsWith("\"") && parameters[0].EndsWith("\"") && int.TryParse(parameters[1], out difficultyInt) && Enum.IsDefined(typeof(EntryDifficulty), difficultyInt)) { parameterCollection.Add("immediate"); parameterCollection.Add(parameters[0].Substring(1, parameters[0].Length - 2)); parameterCollection.Add(parameters[1]); return parameterCollection; } break; } return null; }
/// <summary> /// Parse a query string /// </summary> /// <param name="reader">string to parse</param> /// <returns>A collection</returns> /// <exception cref="ArgumentNullException"><c>reader</c> is <c>null</c>.</exception> public static ParameterCollection Parse(ITextReader reader) { if (reader == null) throw new ArgumentNullException("reader"); var parameters = new ParameterCollection(); while (!reader.EOF) { string name = HttpUtility.UrlDecode(reader.ReadToEnd("&=")); char current = reader.Current; reader.Consume(); switch (current) { case '&': parameters.Add(name, string.Empty); break; case '=': { string value = reader.ReadToEnd("&"); reader.Consume(); parameters.Add(name, HttpUtility.UrlDecode(value)); } break; default: parameters.Add(name, string.Empty); break; } } return parameters; }
public static WikiPage Load(Wiki wiki, string title, string directory) { ParameterCollection parameters = new ParameterCollection(); parameters.Add("prop", "info|revisions"); parameters.Add("intoken", "edit"); parameters.Add("rvprop", "timestamp"); XmlDocument xml = wiki.Query(QueryBy.Titles, parameters, new string[] { title }); XmlNode node = xml.SelectSingleNode("//rev"); string baseTimeStamp = null; if (node != null && node.Attributes["timestamp"] != null) { baseTimeStamp = node.Attributes["timestamp"].Value; } node = xml.SelectSingleNode("//page"); string editToken = node.Attributes["edittoken"].Value; string pageFileName = directory + EscapePath(title); string text = LoadPageFromCache(pageFileName, node.Attributes["lastrevid"].Value, title); if (string.IsNullOrEmpty(text)) { Console.Out.WriteLine("Downloading " + title + "..."); text = wiki.LoadText(title); CachePage(pageFileName, node.Attributes["lastrevid"].Value, text); } WikiPage page = WikiPage.Parse(title, text); page.BaseTimestamp = baseTimeStamp; page.Token = editToken; return page; }
protected EmployeeCollection GetCollection(GetItemType SelectType, string SearchString, int ReturnCount) { //notes: return collection of groups string strStoredProcName = "Elite_GetEmployee"; try { //notes: get base object properties you want hydrated and add any additional if necessary ObjectPropertyDictionary objProperties = this.GetBaseProperties(); objProperties.Add("label", SqlDbType.VarChar); objProperties.Add("value", SqlDbType.VarChar); //notes: set the parameters to use for this query ParameterCollection objParamCollection = new ParameterCollection(); objParamCollection.Add(ReturnCount.GetParameterInt("@ReturnCount")); switch (SelectType) { case GetItemType.BY_SEARCH: // 21 = GET_COLLECTION_BY_SEARCH objParamCollection.Add((21).GetParameterListValue()); objParamCollection.Add(SearchString.GetParameterVarchar("@SearchString", 300)); break; } //notes: call local method to get list return this.GetLocalCollection(objParamCollection, objProperties, strStoredProcName); } catch (Exception ex) { return new EmployeeCollection { StatusResult = new ResponseStatus("Get Employee Search Collection Error: " + ex.Message, ex.StackTrace, ResponseStatusResult.Fail) }; } }
public ParameterCollection CheckParameters(string[] parameters) { ParameterCollection parameterCollection = new ParameterCollection(); switch (parameters.Length) { case 0: parameterCollection.Add("create"); return parameterCollection; case 1: if (parameters[0] == "show") { parameterCollection.Add("show"); return parameterCollection; } break; case 2: if (parameters[0] == "restore" && parameters[1].Length == 15) { parameterCollection.Add("restore"); parameterCollection.Add(parameters[1]); return parameterCollection; } break; } return null; }
protected VendorItem GetItem(GetItemType SelectType, int VendorID) { string strStoredProcName = "jsp_Subscription_GetVendorItems"; try { //notes: set the parameters to use for this query ParameterCollection objParamCollection = new ParameterCollection(); switch (SelectType) { case GetItemType.BY_ID: objParamCollection.Add((10).GetParameterListValue()); objParamCollection.Add(VendorID.GetParameterInt("@VendorID")); break; } //notes: get base object properties you want hydrated and add any additional if necessary ObjectPropertyDictionary objProperties = this.GetBaseProperties(); //notes: call local method to get object item return this.GetLocalItem(objParamCollection, objProperties, strStoredProcName); } catch (Exception ex) { return new VendorItem { StatusResult = new ResponseStatus("Get Vendor Item Error: " + ex.Message, ex.StackTrace, ResponseStatusResult.Fail) }; } }
public void CanConcatParameter() { var parameters = new ParameterCollection(); parameters.Add(new BasicParameter() { ParameterName = "param1", ParameterValue = "SharpDevelop" } ); parameters.Add(new BasicParameter() { ParameterName = "param2", ParameterValue = " is " } ); parameters.Add(new BasicParameter() { ParameterName = "param3", ParameterValue = "great" } ); var reportSettings = CreateReportSettings(parameters); var visitor = new ExpressionVisitor(reportSettings); var script = "=Parameters!param1 + Parameters!param2 + Parameters!param3"; collection[0].Text = script; visitor.Visit(collection[0]); Assert.That (collection[0].Text,Is.EqualTo("SharpDevelop is great")); }
public void DuplicateTest() { var col = new ParameterCollection(); col.Add("chocolate", "cookie"); col.Add("chocolate", "bar"); col.Add("chocolate", "pudding"); Assert.That(col.Count, Is.EqualTo(3)); CollectionAssert.AreEqual(new[] { "cookie", "bar", "pudding" }, col.GetAllMatches("chocolate")); }
public string GetUrlParameters() { var parameters = new ParameterCollection(); parameters.Add("routing", _routing, _routingSet); parameters.Add("pretty", "true", _prettySet); parameters.Add("search_type", _seachType.ToString(), _seachTypeSet); parameters.Add("query_cache", _queryCache.ToString().ToLower(), _queryCacheSet); return parameters.ToString(); }
public DTMFFacilityRequestParameter() { _parameters = new ParameterCollection(); // FacilityFunction _parameters.Add(new Parameter<short>()); // Tone Duration _parameters.Add(new Parameter<short>(40)); // Gap Duration _parameters.Add(new Parameter<short>(40)); // DTMF digits _parameters.Add(new Parameter<string>()); // DTMF Characteristics _parameters.Add(new Parameter<short>()); }
public void ActivateUser(User user, string password) { string customerSupportEmail = systemService.GetConfig<string>(Constants.Settings.CustomerSupportEmail, "*****@*****.**"); string emailTemplatePath = Path.Combine(this.emailTemplatesFolder, string.Format("{0}.xml", "ApprovedUser")); ParameterCollection parameters = new ParameterCollection(); parameters.Add("FromMail", customerSupportEmail); parameters.Add("ToMail", user.Email); parameters.Add("Username", user.Username); parameters.Add("Password", password); EmailTemplate emailTemplate = EmailUtility.ComposeTemplate(emailTemplatePath, parameters); emailSender.Send(emailTemplate, new BypassEmailFormatter(), null); }
public static string GetRoutingUrl(RoutingDefinition routingDefinition) { var parameters = new ParameterCollection(); if (routingDefinition != null && routingDefinition.ParentId != null) { parameters.Add("parent", routingDefinition.ParentId.ToString()); } if (routingDefinition != null && routingDefinition.RoutingId != null) { parameters.Add("routing", routingDefinition.RoutingId.ToString()); } return parameters.ToString(); }
protected EmployeeCollection GetCollection() { //notes: return collection of groups string strStoredProcName = "Elite_GetEmployee"; try { //notes: set the parameters to use for this query ParameterCollection objParamCollection = new ParameterCollection(); //notes: ListValue options // 20 = GET_COLLECTION objParamCollection.Add((20).GetParameterListValue()); //notes: get base object properties you want hydrated and add any additional if necessary ObjectPropertyDictionary objProperties = this.GetBaseProperties(); //notes: call local method to get list return this.GetLocalCollection(objParamCollection, objProperties, strStoredProcName); } catch (Exception ex) { return new EmployeeCollection { StatusResult = new ResponseStatus("Get Employee Collection Error: " + ex.Message, ex.StackTrace, ResponseStatusResult.Fail) }; } }
public void GetItemFromCollectionTest() { var parameters = new ParameterCollection(); parameters.Add(new Parameter("x", 2.3)); Assert.AreEqual(2.3, parameters["x"]); }
protected SubscriptionItemCollection GetCollection(GetItemType SelectType) { //notes: return collection of groups string strStoredProcName = "jsp_Subscription_GetSubscriptionItems"; try { //notes: get base object properties you want hydrated and add any additional if necessary ObjectPropertyDictionary objProperties = this.GetBaseProperties(); objProperties.Add("EmployeeName", SqlDbType.VarChar); //notes: set the parameters to use for this query ParameterCollection objParamCollection = new ParameterCollection(); switch (SelectType) { case GetItemType.BY_ALL: objParamCollection.Add((20).GetParameterListValue()); break; } //notes: call local method to get list return this.GetLocalCollection(objParamCollection, objProperties, strStoredProcName); } catch (Exception ex) { return new SubscriptionItemCollection { StatusResult = new ResponseStatus("Get Subscription Collection Error: " + ex.Message, ex.StackTrace, ResponseStatusResult.Fail) }; } }
/// <summary> /// Build parameters from dictionary. /// </summary> internal static ParameterCollection Parametalize(this Dictionary<string, object> dict) { var ret = new ParameterCollection(); dict.Keys.Select(key => new { key, value = dict[key] }) .Where(t => t.value != null) .ForEach(t => ret.Add(new Parameter(t.key, t.value))); return ret; }
public void ChangeEmail(User user) { string customerSupportEmail = systemService.GetConfig<string>(Constants.Settings.CustomerSupportEmail, "*****@*****.**"); string emailTemplatePath = Path.Combine(this.emailTemplatesFolder, string.Format("{0}.xml", "ChangeEmail")); ParameterCollection parameters = new ParameterCollection(); parameters.Add("FromMail", customerSupportEmail); parameters.Add("ToMail", user.Email); parameters.Add("Username", user.Username); string emailBase64String = Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes(user.Email)); string activateAccountUrl = systemService.GetConfig<string>(Constants.Settings.BaseUrl, ""); activateAccountUrl = System.Text.RegularExpressions.Regex.Replace(activateAccountUrl, @"[a-z]{2}\-[A-Z]{2}", Thread.CurrentThread.CurrentCulture.Name); parameters.Add("Url", string.Format("{0}/home/changeemail/{1}", activateAccountUrl.Trim('/'), emailBase64String)); EmailTemplate emailTemplate = EmailUtility.ComposeTemplate(emailTemplatePath, parameters); emailSender.Send(emailTemplate, new BypassEmailFormatter(), null); }
public void OverrideRemoveTest() { var parameters = new ParameterCollection(); parameters.Add(new Parameter("a", 1)); parameters["a"] = 2; parameters.Remove("a"); Assert.AreEqual(0, parameters.Collection.Count()); }
public void SetExistItemFromCollectionTest() { var parameters = new ParameterCollection(); parameters.Add(new Parameter("x", 2.3)); parameters["x"] = 3.3; Assert.AreEqual(1, parameters.Collection.Count()); Assert.IsTrue(parameters.ContainsKey("x")); Assert.AreEqual(3.3, parameters["x"]); }
public void MultipleAddTest() { var col = new ParameterCollection(); // 1. Empty case. Assert.That(col.Count, Is.EqualTo(0)); CollectionAssert.AreEqual(new string[0], col.GetAllMatches("test")); // 2. One element. col.Add("black", "hole"); Assert.That(col.Count, Is.EqualTo(1)); CollectionAssert.AreEqual(new[] { "hole" }, col.GetAllMatches("black")); // 3. Another element. col.Add("white", "dwarf"); Assert.That(col.Count, Is.EqualTo(2)); CollectionAssert.AreEqual(new[] { "hole" }, col.GetAllMatches("black")); CollectionAssert.AreEqual(new[] { "dwarf" }, col.GetAllMatches("white")); }
public List<Lotto> CheckLotto(bool incBonusNumber, params int[] numbers) { List<Lotto> resultSet = new List<Lotto>(); string inCondition = String.Empty; // in 조건에 사용될 컬럼이름 inCondition = "num1 , num2, num3, num4, num5, num6"; if (incBonusNumber) { inCondition += ", numBonus"; } ParameterCollection parameters = new ParameterCollection(); string select = @"select * from lotto where 1 = 1"; for (int i = 0; i < numbers.Length; i++) { select += String.Format(" and @num{0} in ({1})", i + 1, inCondition); parameters.Add(String.Format("@num{0}", i + 1), numbers[i]); } select += " order by Id desc"; DataService dao = new DataService(); dao.SetConnectionString(this.GetConnectionString()); dao.AddRequestService(CommandType.Text, select, parameters, ExecuteType.ExecuteQuery); List<ResponseService> responses = dao.Execute(); if (dao.HasError) { Logger.Error(dao.GetType(), dao.ErrorMessage); DebugHelper.WriteLine(dao.ErrorMessage); } else { if (responses[0].DataSet.Tables.Count == 0) { DebugHelper.WriteLine("Table is not exists."); } else { resultSet = responses[0].DataSet.Tables[0].Select().Select(r => new Lotto() { Id = Convert.ToInt32(r["Id"]), Dt = String.Format("{0}", r["Dt"]), Num1 = Convert.ToInt32(r["Num1"]), Num2 = Convert.ToInt32(r["Num2"]), Num3 = Convert.ToInt32(r["Num3"]), Num4 = Convert.ToInt32(r["Num4"]), Num5 = Convert.ToInt32(r["Num5"]), Num6 = Convert.ToInt32(r["Num6"]), NumBonus = Convert.ToInt32(r["NumBonus"]), }).ToList(); } } return resultSet; }
public override IObservable<bool> Scrap(string url, string title = null, long? sourceTweetId = null) { var client = new OAuthClient(consumerKey, consumerSecret, new AccessToken(userToken, userSecret)); client.Url = "https://www.readability.com/api/rest/v1/bookmarks"; var param = new ParameterCollection(); param.Add("url", HttpUtility.UrlEncode(url)); client.Parameters = param; client.MethodType = MethodType.Post; return client.GetResponseText() .Select(_ => true); }
protected ParameterCollection ConstructBasicParameters(string url, MethodType methodType, Token token, IEnumerable<Parameter> optionalParameters) { Guard.ArgumentNull(url, "url"); Guard.ArgumentNull(methodType, "methodType"); Guard.ArgumentNull(optionalParameters, "optionalParameters"); var parameters = new ParameterCollection { { "oauth_consumer_key", ConsumerKey }, { "oauth_nonce", random.Next() }, { "oauth_timestamp", DateTime.UtcNow.ToUnixTime() }, { "oauth_signature_method", "HMAC-SHA1" }, { "oauth_version", "1.0" } }; if (token != null) parameters.Add("oauth_token", token.Key); var signature = GenerateSignature(new Uri(url), methodType, token, parameters.Concat(optionalParameters)); parameters.Add("oauth_signature", signature); return parameters; }
/// <summary> /// Gets a string that can be given to the MediaPortal Url Source Splitter holding the url and all parameters. /// </summary> internal override string ToFilterString() { ParameterCollection parameters = new ParameterCollection(); if (this.SegmentFragmentUrlExtraParameters != AfhsManifestUrl.DefaultSegmentFragmentUrlExtraParameters) { parameters.Add(new Parameter(AfhsManifestUrl.ParameterSegmentFragmentUrlExtraParameters, this.SegmentFragmentUrlExtraParameters)); } // return formatted connection string return base.ToFilterString() + ParameterCollection.ParameterSeparator + parameters.FilterParameters; }
public void CalculateTest() { var exp = parser.Parse("~a"); var parameters = new ParameterCollection(); parameters.Add("a"); parameters["a"] = true; Assert.IsFalse((bool)exp.Calculate(parameters)); parameters["a"] = false; Assert.IsTrue((bool)exp.Calculate(parameters)); }
public ParameterCollection CheckParameters(string[] parameters) { ParameterCollection parameterCollection = new ParameterCollection(); switch (parameters.Length) { case 0: parameterCollection.Add("summary"); return parameterCollection; case 1: if (CommandsHelp.Keys.Contains(parameters[0].ToLowerInvariant())) { parameterCollection.Add("command"); parameterCollection.Add(parameters[0].ToLowerInvariant()); return parameterCollection; } break; } return null; }
public void ToString_PrintsCorrectly(IDictionary<string, string> parameters, string expected) { // Arrange ParameterCollection collection = new ParameterCollection(); foreach (var parameter in parameters) { collection.Add(parameter.Key, parameter.Value); } // Act string actual = collection.ToString(); // Assert Assert.Equal(expected, actual); }
public int GetMaxCode(string itemKey) { if (itemKey.Contains("dbo")) { itemKey = itemKey.Remove(0, 4); } ParameterCollection pc = new ParameterCollection(); pc.Add("ITEMKEY", itemKey); try { return (int)this.DataAccessor.Query("exec PDM_GETIDENTITYVALUE @itemkey=?", pc); } catch { throw new System.Exception("读取最大ID时发生错误,错误可能是由于在最大号存储表中没有指定的ItemKey:" + itemKey + ",请参考错误信息修改此问题"); } }
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { SharpQuerySchemaClassCollection tmp= value as SharpQuerySchemaClassCollection; if (destinationType == typeof (ParameterCollection)) { ParameterCollection a = new ParameterCollection(); foreach (SharpQueryParameter par in tmp){ SqlParameter reportPar = new SqlParameter (par.Name, par.DataType, String.Empty, par.Type); reportPar.ParameterValue = par.Value.ToString(); a.Add(reportPar); } return a; } return base.ConvertTo(context, culture, value, destinationType); }
public string ToString(IModel mode, ParameterCollection paramlist) { ValuePair val = this; StringBuilder sbder = new StringBuilder(); var diccols = MReflection.GetModelColumns(mode); if (!diccols.ContainsKey(val.Name)) { return ""; } do { string colname = diccols[val.Name]; if (!string.IsNullOrEmpty(colname)) { var pam = DbEngine.Instance.NewDataParameter(colname); switch (colname) { case "lastchange_time": pam.Value = DateTime.Now; break; default: pam.Value = val.Value; if (pam.Value == null) { pam.Value = ""; } break; } string ptname = paramlist.Add(colname, pam); pam.ParameterName = ptname; sbder.AppendFormat(",{0}={1}", colname, pam.ParameterName); } val = val.Right; } while (val != null); if (sbder.Length > 0) { return sbder.ToString().Substring(1); } return ""; }
public void UpdateNotesFormSRToWOTestMethod() { using (ShimsContext.Create()) { UpdateNotesFormSRToWO updateNotesFormSRToWO = new UpdateNotesFormSRToWO(); var serviceProvider = new StubIServiceProvider(); var pluginContext = new StubIPluginExecutionContext(); var organizationService = new StubIOrganizationService(); pluginContext.PrimaryEntityNameGet = () => "annotation"; pluginContext.PrimaryEntityIdGet = () => new Guid("54D94FC2-52AD-E511-8158-1458D04DB4D1"); ParameterCollection paramCollection = new ParameterCollection(); Entity annotation = new Entity("annotation"); annotation.Attributes["objectid"] = new EntityReference("incident", new Guid("884A078B-0467-E711-80F5-3863BB3C0660")); annotation.Id = new Guid("884A078B-0466-E711-80F5-3863BB3C0560"); annotation.Attributes["filename"] = "filename"; annotation.Attributes["documentbody"] = "documentbody"; annotation.Attributes["notetext"] = "notetext"; annotation.Attributes["objecttypecode"] = "objecttypecode"; annotation.Attributes["mimetype"] = "mimetype"; annotation.Attributes["subject"] = "subject"; paramCollection.Add("Target", annotation); pluginContext.InputParametersGet = () => paramCollection; PluginVariables(serviceProvider, pluginContext, organizationService, 40, "Create"); organizationService.RetrieveMultipleQueryBase = (query) => { EntityCollection collection = new EntityCollection(); string entityName = string.Empty; if (query.GetType().Name.Equals("FetchExpression")) { if (((Microsoft.Xrm.Sdk.Query.FetchExpression)query).Query.Contains("<entity name='ava_keyvaluepair'>")) { entityName = "ava_keyvaluepair"; } } else if (query.GetType().Name.Equals("QueryExpression")) { entityName = ((QueryExpression)query).EntityName; } else { entityName = ((QueryByAttribute)query).EntityName; } if (entityName == "msdyn_workorder") { Entity workorder = new Entity("msdyn_workorder"); workorder.Id = new Guid("884A078B-0467-E711-80F5-3863BB3C0660"); collection.Entities.Add(workorder); } return(collection); }; updateNotesFormSRToWO.Execute(serviceProvider); } }
protected override void OnCalculateScale() { IBarsData bars = this.Owner.Owner.Bars; if (_currentIV == null || _currentIV.TimeFrame.Second != this.Owner.Owner.Bars.TimeFrame.Second) { _views.TryGetValue(bars.TimeFrame.Second, out _currentIV); if (_currentIV == null) { ParameterCollection inputs = new ParameterCollection(); inputs.AddRange(_classBuilder.Parameters); Parameter iBarsParam = inputs["iBars"]; if (iBarsParam == null) { iBarsParam = new Parameter(this.iBars, "iBars"); inputs.Add(iBarsParam); } iBarsParam.Value = this.iBars; Indicator indicator = _classBuilder.CreateInstance(inputs.ToArray()) as Indicator; PropertyInfo[] properties = _classBuilder.ClassType.GetProperties(); List <FunctionViewInfo> functions = new List <FunctionViewInfo>(); foreach (PropertyInfo property in properties) { FunctionViewInfo fview = new FunctionViewInfo(property); if ((int)fview.Error == -1) { functions.Add(fview); fview.Join(indicator); } } _currentIV = new IndicatorView(bars.TimeFrame, indicator, functions.ToArray()); _views.Add(bars.TimeFrame.Second, _currentIV); } _savedCountTick = -1; } int countTick = this.Owner.Owner.Symbol.Ticks.Count; int beginIndex = this.Owner.HorizontalScale.Position; if (_savedCountTick == countTick && _savedPosition == beginIndex && _savedWidth == this.Owner.Width) { return; } _savedCountTick = countTick; _savedPosition = beginIndex; _savedWidth = this.Owner.Width; int cntBarW = this.Owner.HorizontalScale.CountBarView; int endIndex = beginIndex + cntBarW; int countBar = bars.Count; this.iBars.Limit = this.LimitCompute; this.iBars.SetLimit(beginIndex, cntBarW); endIndex = Math.Min(endIndex, countBar); if (endIndex - beginIndex == 0) { return; } float min = float.MaxValue; float max = float.MinValue; FunctionViewInfo[] fvs = _currentIV.FunctionsView; float val = float.NaN; for (int j = 0; j < fvs.Length; j++) { Function f = fvs[j].Function as Function; f.NativeCompute(); for (int i = beginIndex; i < endIndex; i++) { val = f.NativeGetItem(i); if (!float.IsNaN(val)) { min = Math.Min(min, val); max = Math.Max(max, val); } } } this.Owner.VerticalScale.SetScaleValue(min, max, this.Owner.Owner.Symbol.Digits); }
public void ReadArguments(string[] parameters) { if (parameters.Length == 0) { //throw new Exception("No parameter is specified!"); GetHelp = true; } #region Assigning crexport parameters to variables for (int i = 0; i < parameters.Count(); i++) { if (i + 1 < parameters.Count()) { if (parameters[i + 1].Length > 0) { if (parameters[i].ToUpper() == "-U") { UserName = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-P") { Password = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-F") { ReportPath = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-O") { OutputPath = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-S") { ServerName = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-D") { DatabaseName = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-E") { OutputFormat = parameters[i + 1]; if (OutputFormat.ToUpper() == "PRINT") { PrintOutput = true; } } else if (parameters[i].ToUpper() == "-N") { PrinterName = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-C") { try { PrintCopy = Convert.ToInt32(parameters[i + 1]); } catch (Exception ex) { throw ex; } } else if (parameters[i].ToUpper() == "-A") { ParameterCollection.Add(parameters[i + 1]); } //Email Config else if (parameters[i].ToUpper() == "-M") { EmailOutput = true; } else if (parameters[i].ToUpper() == "-MF") { MailFrom = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-MN") { MailFromName = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-MS") { EmailSubject = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-MI") { EmailBody = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-MT") { MailTo = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-MC") { MailCC = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-MB") { MailBcc = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-MK") { EmailKeepFile = true; } else if (parameters[i].ToUpper() == "-MSA") { SmtpServer = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-MSP") { SmtpPort = Convert.ToInt32(parameters[i + 1]); } else if (parameters[i].ToUpper() == "-MSE") { SmtpSSL = true; } else if (parameters[i].ToUpper() == "-MSC") { SmtpAuth = true; } else if (parameters[i].ToUpper() == "-MUN") { SmtpUN = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-MPW") { SmtpPW = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-SF") { SelectionFormula = parameters[i + 1]; } } } if (parameters[i] == "-?" || parameters[i] == "/?") { GetHelp = true; } if (parameters[i].ToUpper() == "-L") { EnableLog = true; } if (parameters[i].ToUpper() == "-NR") { Refresh = false; } if (parameters[i].ToUpper() == "-LC") { EnableLogToConsole = true; } } #endregion }
public void AttachmentURLUpdateOnNoteDeleteTestMethod() { using (ShimsContext.Create()) { AttachmentURLUpdateOnNoteDelete attachmentURLUpdateOnNoteDelete = new StubAttachmentURLUpdateOnNoteDelete(); var serviceProvider = new StubIServiceProvider(); var pluginContext = new StubIPluginExecutionContext(); var organizationService = new StubIOrganizationService(); pluginContext.PrimaryEntityNameGet = () => "annotation"; pluginContext.PrimaryEntityIdGet = () => new Guid("54D94FC2-52AD-E511-8158-1458D04DB4D1"); ParameterCollection paramCollection = new ParameterCollection(); EntityReference annotation = new EntityReference("annotation"); annotation.Id = new Guid("54D94FC2-52AD-E511-8158-1458D04DB4D1"); paramCollection.Add("Target", annotation); pluginContext.InputParametersGet = () => paramCollection; PluginVariables(serviceProvider, pluginContext, organizationService, 40, "Delete", null); organizationService.RetrieveMultipleQueryBase = (query) => { EntityCollection collection = new EntityCollection(); string entityName = string.Empty; if (query.GetType().Name.Equals("FetchExpression")) { if (((Microsoft.Xrm.Sdk.Query.FetchExpression)query).Query.Contains("<entity name='ava_keyvaluepair'>")) { entityName = "ava_keyvaluepair"; } } else if (query.GetType().Name.Equals("QueryExpression")) { entityName = ((QueryExpression)query).EntityName; } else { entityName = ((QueryByAttribute)query).EntityName; } if (entityName == "msdyn_customerasset") { Entity question = new Entity { LogicalName = "msdyn_customerasset", Id = new Guid("884A078c-0467-E711-80E5-3863BB3C0660") }; //// question.Attributes["smp_questiontext"] = "unittest1"; collection.Entities.Add(question); } if (entityName == "smp_attachmentsurl") { Entity attachmentUrl = new Entity("smp_attachmentsurl"); attachmentUrl.Id = new Guid("884A078B-0467-E711-80F5-3863BB3C0660"); attachmentUrl.Attributes["smp_objectid"] = "54D94FC2-52AD-E511-8158-1458D04DB4D1"; attachmentUrl.Attributes["smp_name"] = "Test"; collection.Entities.Add(attachmentUrl); } return(collection); }; attachmentURLUpdateOnNoteDelete.Execute(serviceProvider); } }
public void ReadArguments(string[] parameters) { Main frm = new Main(); //Utility.WriteActivity("test"); if (parameters.Length == 0) { throw new Exception("No parameter is specified!"); } #region Assigning crexport parameters to variables for (int i = 0; i < parameters.Count(); i++) { if (i + 1 < parameters.Count()) { if (parameters[i + 1].Length > 0) { if (parameters[i].ToUpper() == "-U") { UserName = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-P") { Password = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-F") { ReportPath = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-O") { OutputPath = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-S") { ServerName = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-D") { DatabaseName = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-E") { OutputFormat = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-N") { PrinterName = parameters[i + 1]; } else if (parameters[i].ToUpper() == "-C") { try { PrintCopy = Convert.ToInt32(parameters[i + 1]); } catch (Exception ex) { throw ex; } } else if (parameters[i].ToUpper() == "-A") { ParameterCollection.Add(parameters[i + 1]); } else if (parameters[i].ToUpper() == "-TO") { MailTo = parameters[i + 1]; } } } if (parameters[i] == "-?" || parameters[i] == "/?") { GetHelp = true; } if (parameters[i].ToUpper() == "-L") { EnableLog = true; } if (parameters[i].ToUpper() == "-NR") { Refresh = false; } } #endregion }
/*******************************************************************************/ public void DoPersistWithSpAndParams(HraModelChangedEventArgs e, String spName, ref ParameterCollection sPparams) { lock (BCDB2.Instance) { if (e.Persist == false) { return; } try { ////////////////////// using (SqlConnection connection = new SqlConnection(BCDB2.Instance.getConnectionString())) { connection.Open(); SqlCommand cmdProcedure = new SqlCommand(spName, connection) { CommandType = CommandType.StoredProcedure, CommandTimeout = 300 }; //change command timeout from default to 5 minutes if (e.Delete) { cmdProcedure.Parameters.Add("@delete", SqlDbType.Bit); cmdProcedure.Parameters["@delete"].Value = e.Delete; } cmdProcedure.Parameters.Add("@user", SqlDbType.NVarChar); if (SessionManager.Instance.ActiveUser == null) { cmdProcedure.Parameters["@user"].Value = "Not Available"; } else { cmdProcedure.Parameters["@user"].Value = SessionManager.Instance.ActiveUser.userLogin; } if (sPparams != null) { foreach (string param in sPparams.getKeys()) { if (sPparams[param].Size > 0) { cmdProcedure.Parameters.Add("@" + param, sPparams[param].sqlType, sPparams[param].Size); } else { cmdProcedure.Parameters.Add("@" + param, sPparams[param].sqlType); } cmdProcedure.Parameters["@" + param].Value = sPparams[param].obj; if (sPparams[param].BiDirectional) { cmdProcedure.Parameters["@" + param].Direction = ParameterDirection.InputOutput; } } } try { if (e.updatedMembers.Count > 0) { foreach (FieldInfo fi in this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { string name = fi.Name; foreach (MemberInfo mi in e.updatedMembers) { if (name == mi.Name) { SqlDbType sType = BCDB2.Instance.GetSqlTypeFromModel(fi.FieldType); if (cmdProcedure.Parameters.Contains("@" + name)) { if (cmdProcedure.Parameters["@" + name].Value.Equals(fi.GetValue(this))) { //Logger.Instance.WriteToLog("[DoPersistWithSpAndParams] Executing Stored Procedure - " // + "Added the same parameter and value twice; parameter name = " + name + "; value = " + cmdProcedure.Parameters["@" + name].Value.ToString()); } else { Logger.Instance.WriteToLog("Attempted to Add the same parameter twice with differing values; first value = " + cmdProcedure.Parameters["@" + name].Value + ", " + "Second value = " + fi.GetValue(this)); } break; //don't add it } cmdProcedure.Parameters.Add("@" + name, sType); cmdProcedure.Parameters["@" + name].Value = fi.GetValue(this); break; } } } } else { foreach (FieldInfo fi in this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { bool persist = IsPersistable(fi); if (fi.FieldType == typeof(DateTime)) { DateTime dt = (DateTime)fi.GetValue(this); if (!(dt > DateTime.MinValue && dt < DateTime.MaxValue)) { persist = false; } } else if (fi.GetValue(this) == null) { persist = false; } if (persist) { SqlDbType sType = BCDB2.Instance.GetSqlTypeFromModel(fi.FieldType); if (cmdProcedure.Parameters.Contains("@" + fi.Name)) { if (cmdProcedure.Parameters["@" + fi.Name].Value.Equals(fi.GetValue(this))) { Logger.Instance.WriteToLog("[DoPersistWithSpAndParams] executing Stored Procedure [" + cmdProcedure.CommandText + "] - Added the same parameter and value twice; parameter name = " + fi.Name + "; value = " + cmdProcedure.Parameters["@" + fi.Name].Value); } else { Logger.Instance.WriteToLog("[DoPersistWithSpAndParams] executing Stored Procedure - [" + cmdProcedure.CommandText + "] - Attempted to Add the same parameter twice with differing values; first value = " + cmdProcedure.Parameters["@" + fi.Name].Value + ", " + "Second value = " + fi.GetValue(this)); } continue; //don't add it } cmdProcedure.Parameters.Add("@" + fi.Name, sType); cmdProcedure.Parameters["@" + fi.Name].Value = (fi.GetValue(this) is Double ? (Double.IsNaN((Double)(fi.GetValue(this))) ? null : fi.GetValue(this)) : fi.GetValue(this)); } } } PersistWithSpAndParamsChattyDebug(); cmdProcedure.ExecuteNonQuery(); foreach (SqlParameter p in cmdProcedure.Parameters) { if (p.Direction == ParameterDirection.InputOutput) { if (sPparams != null) { sPparams.Add(p.ParameterName.Replace("@", ""), p.Value); } } } } catch (Exception exception) { Logger.Instance.WriteToLog("[DoPersistWithSpAndParams] Executing Stored Procedure - " + cmdProcedure.CommandText + "; " + exception); } } //end of using connection } catch (Exception exc) { Logger.Instance.WriteToLog("[DoPersistWithSpAndParams] Executing Stored Procedure - " + exc); } } }
public void FSPostUpdateOfServiceRequestStatusTestMethod() { using (ShimsContext.Create()) { FSPostUpdateOfServiceRequestStatus fspostUpdateOfServiceRequestStatus = new StubFSPostUpdateOfServiceRequestStatus(); var serviceProvider = new StubIServiceProvider(); var pluginContext = new StubIPluginExecutionContext(); var organizationService = new StubIOrganizationService(); pluginContext.PrimaryEntityNameGet = () => "incident"; pluginContext.PrimaryEntityIdGet = () => new Guid("54D94FC2-52AD-E511-8158-1458D04DB4D1"); ParameterCollection paramCollection = new ParameterCollection(); Entity targetIncident = new Entity("incident"); targetIncident.Id = new Guid("54D94FC2-52AD-E511-8158-1458D04DB4D1"); targetIncident.Attributes["statuscode"] = new OptionSetValue(180620002); paramCollection.Add("Target", targetIncident); pluginContext.InputParametersGet = () => paramCollection; Entity incidentImage = new Entity("incident"); incidentImage.Id = new Guid("54D94FC2-52AD-E511-8158-1458D04DB4D1"); incidentImage.Attributes["statuscode"] = new OptionSetValue(180620002); incidentImage.Attributes["customerid"] = new EntityReference("account", new Guid("884A078B-0468-E711-80F5-3863BB3C0660")); incidentImage.Attributes["smp_problembuilding"] = new EntityReference("building", new Guid("884A078B-0458-E711-80F5-3863BB3C0660")); incidentImage.Attributes["smp_workorderwithind365"] = true; incidentImage.Attributes["transactioncurrencyid"] = new EntityReference("transactioncurrency", new Guid("884A078B-0468-E721-80F5-3863BB3C0660")); var postImage = new EntityImageCollection { (new KeyValuePair <string, Entity>("PostImage", incidentImage)) }; PluginVariables(serviceProvider, pluginContext, organizationService, 40, "Update", postImage); organizationService.RetrieveMultipleQueryBase = (query) => { EntityCollection collection = new EntityCollection(); string entityName = string.Empty; if (query.GetType().Name.Equals("FetchExpression")) { if (((Microsoft.Xrm.Sdk.Query.FetchExpression)query).Query.Contains("<entity name='ava_keyvaluepair'>")) { entityName = "ava_keyvaluepair"; } } else if (query.GetType().Name.Equals("QueryExpression")) { entityName = ((QueryExpression)query).EntityName; } else { entityName = ((QueryByAttribute)query).EntityName; } if (entityName == "msdyn_workorder") { Entity workorder = new Entity("msdyn_workorder"); workorder.Id = new Guid("884A078B-0467-E711-80F5-3863BB3C0660"); workorder.Attributes["msdyn_servicerequest"] = new Guid("54D94FC2-52AD-E511-8158-1458D04DB4D1"); collection.Entities.Add(workorder); } if (entityName == "pricelevel") { Entity pricelevel = new Entity("pricelevel"); pricelevel.Id = new Guid("884A078B-0468-E712-80F5-3863BB3C0560"); pricelevel.Attributes["name"] = "US"; collection.Entities.Add(pricelevel); } if (entityName == "account") { Entity pricelevel = new Entity("account"); pricelevel.Id = new Guid("884A078B-0468-E712-80F8-3863BB3C0560"); pricelevel.Attributes["name"] = "BuildingName"; collection.Entities.Add(pricelevel); } return(collection); }; organizationService.RetrieveStringGuidColumnSet = delegate(string entity, Guid guid, ColumnSet secondaryUserColumnSet) { if (entity == "account") { Entity incident = new Entity("account"); incident.Id = new Guid("884A078B-0468-E711-80F5-3863BB3C0660"); incident.Attributes["smp_workorderwithind365"] = true; incident.Attributes["msdyn_servicerequest"] = new EntityReference("account", new Guid("884A078B-0468-E711-80F5-3863BB3C0660")); incident.Attributes["msdyn_pricelist"] = new EntityReference("pricelevel", new Guid("884A078B-0468-E712-80F5-3863BB3C0560")); return(incident); } if (entity == "incident") { Entity incident = new Entity("incident"); incident.Id = new Guid("884A078B-0468-E721-80F5-3863BB3C0660"); incident.Attributes["smp_reclassifiedfromworkorder"] = false; return(incident); } return(null); }; fspostUpdateOfServiceRequestStatus.Execute(serviceProvider); } }
public override void ExportToParameters(ParameterCollection p) { if (p == null) { throw new ArgumentNullException(nameof(p)); } base.ExportToParameters(p); { var(n, f) = Utils.CoordToDxpFrac(Location.X); if (n != 0 || f != 0) { p.Add("LOCATION.X", n); } if (f != 0) { p.Add("LOCATION.X" + "_FRAC", f); } } { var(n, f) = Utils.CoordToDxpFrac(Location.Y); if (n != 0 || f != 0) { p.Add("LOCATION.Y", n); } if (f != 0) { p.Add("LOCATION.Y" + "_FRAC", f); } } { var(n, f) = Utils.CoordToDxpFrac(Radius); if (n != 0 || f != 0) { p.Add("RADIUS", n); } if (f != 0) { p.Add("RADIUS" + "_FRAC", f); } } { var(n, f) = Utils.CoordToDxpFrac(SecondaryRadius); if (n != 0 || f != 0) { p.Add("SECONDARYRADIUS", n); } if (f != 0) { p.Add("SECONDARYRADIUS" + "_FRAC", f); } } p.Add("LINEWIDTH", LineWidth); p.Add("STARTANGLE", StartAngle); p.Add("ENDANGLE", EndAngle); p.Add("COLOR", Color); }
public override void Execute() { string name = string.Empty; try { OnDocColEvent(new ETLEventArgs { Message = "[" + Contract + "] Loading users.", IsError = false }); ConcurrentBag <ERecentUserList> recentList = new ConcurrentBag <ERecentUserList>(); ConcurrentBag <MEContact> contacts; using (ContactMongoContext cctx = new ContactMongoContext(Contract)) { contacts = new ConcurrentBag <MEContact>(cctx.Contacts.Collection.FindAllAs <MEContact>().ToList()); } Parallel.ForEach(contacts, contact => //foreach (MEContact contact in contacts)//.Where(t => !t.DeleteFlag)) { name = contact.LastName + ", " + contact.FirstName; if (contact.PatientId == null) { try { ParameterCollection parms = new ParameterCollection(); parms.Add(new Parameter("@MongoID", contact.Id.ToString(), SqlDbType.VarChar, ParameterDirection.Input, 50)); parms.Add(new Parameter("@ResourceId", (string.IsNullOrEmpty(contact.ResourceId) ? string.Empty : contact.ResourceId), SqlDbType.VarChar, ParameterDirection.Input, 50)); parms.Add(new Parameter("@FirstName", (string.IsNullOrEmpty(contact.FirstName) ? string.Empty : contact.FirstName), SqlDbType.VarChar, ParameterDirection.Input, 50)); parms.Add(new Parameter("@LastName", (string.IsNullOrEmpty(contact.LastName) ? string.Empty : contact.LastName), SqlDbType.VarChar, ParameterDirection.Input, 50)); parms.Add(new Parameter("@PreferredName", (string.IsNullOrEmpty(contact.PreferredName) ? string.Empty : contact.PreferredName), SqlDbType.VarChar, ParameterDirection.Input, 50)); parms.Add(new Parameter("@Version", contact.Version, SqlDbType.Float, ParameterDirection.Input, 32)); parms.Add(new Parameter("@UpdatedBy", (string.IsNullOrEmpty(contact.UpdatedBy.ToString()) ? string.Empty : contact.UpdatedBy.ToString()), SqlDbType.VarChar, ParameterDirection.Input, 50)); parms.Add(new Parameter("@LastUpdatedOn", contact.LastUpdatedOn ?? (object)DBNull.Value, SqlDbType.DateTime, ParameterDirection.Input, 50)); parms.Add(new Parameter("@RecordCreatedBy", (string.IsNullOrEmpty(contact.RecordCreatedBy.ToString()) ? string.Empty : contact.RecordCreatedBy.ToString()), SqlDbType.VarChar, ParameterDirection.Input, 50)); parms.Add(new Parameter("@RecordCreatedOn", contact.RecordCreatedOn, SqlDbType.DateTime, ParameterDirection.Input, 50)); parms.Add(new Parameter("@Delete", (string.IsNullOrEmpty(contact.DeleteFlag.ToString()) ? string.Empty : contact.DeleteFlag.ToString()), SqlDbType.VarChar, ParameterDirection.Input, 50)); parms.Add(new Parameter("@TTLDate", contact.TTLDate ?? (object)DBNull.Value, SqlDbType.DateTime, ParameterDirection.Input, 50)); SQLDataService.Instance.ExecuteProcedure(Contract, true, "REPORT", "spPhy_RPT_SaveUser", parms); if (contact.RecentList != null) { foreach (var rec in contact.RecentList) { recentList.Add(new ERecentUserList { MongoId = rec.ToString(), MongoUserId = (string.IsNullOrEmpty(contact.Id.ToString()) ? string.Empty : contact.Id.ToString()), Version = Convert.ToInt32(contact.Version), MongoUpdatedBy = (string.IsNullOrEmpty(contact.UpdatedBy.ToString()) ? string.Empty : contact.UpdatedBy.ToString()), LastUpdatedOn = contact.LastUpdatedOn, MongoRecordCreatedBy = (string.IsNullOrEmpty(contact.RecordCreatedBy.ToString()) ? string.Empty : contact.RecordCreatedBy.ToString()), RecordCreatedOn = contact.RecordCreatedOn }); } } } catch (Exception ex) { OnDocColEvent(new ETLEventArgs { Message = "[" + Contract + "] name: " + name + ": " + ex.Message + ": " + ex.StackTrace, IsError = true }); } } }); SaveSubcollection(recentList.ToList()); } catch (Exception ex) { OnDocColEvent(new ETLEventArgs { Message = "[" + Contract + "] LoadUsers():: name: " + name + ": " + ex.Message + ": " + ex.StackTrace, IsError = true }); } }
public void WhenChangeOrderIsCreatedFromInstalledBaseLineAndCustomerDetailsArePresentThenACommercialOrderIsCreated() { var postChangeOrderDetailsCreate = new PostChangeOrderDetailsCreate(); var serviceProvider = new StubIServiceProvider(); var tracingService = new StubITracingService(); var pluginContext = new StubIPluginExecutionContext(); var organizationService = new StubIOrganizationService(); PluginTestsHelper.MolePluginVariables(serviceProvider, pluginContext, organizationService, 40, "Create"); var entityAttributes = new Dictionary <string, object>(); Entity changeOrderDetailsEntity = new Entity(); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.IsCreatedFromInstalledBaseLine, true); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.SelectedInstalledBaseLineGuids, "\"B344FF0E - 2567 - E711 - 81A5 - 000D3A275BAD\",\"BB5F3570 - 1466 - E711 - 81A3 - 000D3A275BAD\""); pluginContext.InputParametersGet = delegate { ParameterCollection parameterCollection = new ParameterCollection(); parameterCollection.Add("Target", changeOrderDetailsEntity); return(parameterCollection); }; // Installed Base Line and Account organizationService.RetrieveStringGuidColumnSet = (entityName, recordId, columns) => { if (string.Compare(entityName, InstalledBaseLineEntity.EntitySchemaName, StringComparison.CurrentCultureIgnoreCase) == 0) { var installedBaseLineEntity = new Entity(); installedBaseLineEntity.Id = Guid.NewGuid(); installedBaseLineEntity.Attributes.Add(InstalledBaseLineEntity.BillingModel, new OptionSetValue(4256364)); installedBaseLineEntity.Attributes.Add(InstalledBaseLineEntity.PriceList, new EntityReference("pricelevel", Guid.NewGuid())); return(installedBaseLineEntity); } else if (string.Compare(entityName, InstalledBaseEntity.EntitySchemaName, StringComparison.CurrentCultureIgnoreCase) == 0) { var installedBaseEntity = new Entity(); installedBaseEntity.Id = Guid.NewGuid(); installedBaseEntity.Attributes.Add(InstalledBaseEntity.ContractId, "ContractABC"); installedBaseEntity.Attributes.Add(InstalledBaseEntity.Customer, new EntityReference(AccountEntity.EntitySchemaName, Guid.NewGuid())); installedBaseEntity.Attributes.Add(InstalledBaseEntity.Currency, new EntityReference("transactioncurrencyid", Guid.NewGuid())); return(installedBaseEntity); } else if (string.Compare(entityName, AccountEntity.EntitySchemaName, StringComparison.CurrentCultureIgnoreCase) == 0) { var accountEntity = new Entity(); accountEntity.Id = Guid.NewGuid(); accountEntity.Attributes.Add(AccountEntity.AccountManager, new EntityReference("systemuser", Guid.NewGuid())); accountEntity.Attributes.Add(AccountEntity.TechnicalContact, new EntityReference("contact", Guid.NewGuid())); accountEntity.Attributes.Add(AccountEntity.BillingContact, new EntityReference("contact", Guid.NewGuid())); return(accountEntity); } return(null); }; organizationService.CreateEntity = (e) => { return(Guid.NewGuid()); }; var selectedInstalledBaseLineEntities = TestDataCreator.GetSelectedInstalledBaseLineRecords(5); var commercialOrderRecord = PostChangeOrderDetailsCreate.GetDetailsToCreateAndCreateCommercialOrderRecordFromDetailsInInstalledBaseAndCustomer(organizationService, tracingService, selectedInstalledBaseLineEntities, changeOrderDetailsEntity); Assert.IsNotNull(commercialOrderRecord); Assert.IsTrue(commercialOrderRecord.Id != Guid.Empty); }
public void WhenAllChangeOrderDetailsCreationDetailsArePresentChangeOrderDetailsAreCreated() { var postChangeOrderDetailsCreate = new PostChangeOrderDetailsCreate(); var serviceProvider = new StubIServiceProvider(); var tracingService = new StubITracingService(); var pluginContext = new StubIPluginExecutionContext(); var organizationService = new StubIOrganizationService(); PluginTestsHelper.MolePluginVariables(serviceProvider, pluginContext, organizationService, 40, "Create"); var entityAttributes = new Dictionary <string, object>(); Entity changeOrderDetailsEntity = new Entity(); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.IsCreatedFromInstalledBaseLine, true); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.SelectedInstalledBaseLineGuids, "\"B344FF0E - 2567 - E711 - 81A5 - 000D3A275BAD\",\"BB5F3570 - 1466 - E711 - 81A3 - 000D3A275BAD\""); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.Operation, new OptionSetValue(10000)); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.OrderType, new OptionSetValue(10000)); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.Product, new EntityReference("product", Guid.NewGuid())); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.OldCustomer, new EntityReference("contact", Guid.NewGuid())); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.OldBranch, new EntityReference("account", Guid.NewGuid())); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.NewBranch, new EntityReference("account", Guid.NewGuid())); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.ScheduleTerminationDuration, 6453); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.ScheduleUnits, false); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.SalesTerminationReason, new OptionSetValue(10000)); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.BillingTerminationReason, new OptionSetValue(10001)); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.HardwareTerminationReason, new OptionSetValue(10002)); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.AddOnTerminationReason, new OptionSetValue(10003)); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.SalesSuspensionReason, new OptionSetValue(10004)); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.BillingSuspensionReason, new OptionSetValue(10005)); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.SalesReactivationReason, new OptionSetValue(10004)); changeOrderDetailsEntity.Attributes.Add(ChangeOrderDetailsEntity.BillingReactivationReason, new OptionSetValue(10002)); pluginContext.InputParametersGet = delegate { ParameterCollection parameterCollection = new ParameterCollection(); parameterCollection.Add("Target", changeOrderDetailsEntity); return(parameterCollection); }; // Installed Base Line and Account organizationService.RetrieveStringGuidColumnSet = (entityName, recordId, columns) => { if (string.Compare(entityName, InstalledBaseLineEntity.EntitySchemaName, StringComparison.CurrentCultureIgnoreCase) == 0) { var installedBaseLineEntity = new Entity(); installedBaseLineEntity.Id = Guid.NewGuid(); installedBaseLineEntity.Attributes.Add(InstalledBaseLineEntity.BillingModel, new OptionSetValue(4256364)); installedBaseLineEntity.Attributes.Add(InstalledBaseLineEntity.PriceList, new EntityReference("pricelevel", Guid.NewGuid())); return(installedBaseLineEntity); } else if (string.Compare(entityName, InstalledBaseEntity.EntitySchemaName, StringComparison.CurrentCultureIgnoreCase) == 0) { var installedBaseEntity = new Entity(); installedBaseEntity.Id = Guid.NewGuid(); installedBaseEntity.Attributes.Add(InstalledBaseEntity.ContractId, "ContractABC"); installedBaseEntity.Attributes.Add(InstalledBaseEntity.Customer, new EntityReference(AccountEntity.EntitySchemaName, Guid.NewGuid())); installedBaseEntity.Attributes.Add(InstalledBaseEntity.Currency, new EntityReference("transactioncurrencyid", Guid.NewGuid())); return(installedBaseEntity); } else if (string.Compare(entityName, AccountEntity.EntitySchemaName, StringComparison.CurrentCultureIgnoreCase) == 0) { var accountEntity = new Entity(); accountEntity.Id = Guid.NewGuid(); accountEntity.Attributes.Add(AccountEntity.AccountManager, new EntityReference("systemuser", Guid.NewGuid())); accountEntity.Attributes.Add(AccountEntity.TechnicalContact, new EntityReference("contact", Guid.NewGuid())); accountEntity.Attributes.Add(AccountEntity.BillingContact, new EntityReference("contact", Guid.NewGuid())); return(accountEntity); } return(null); }; organizationService.CreateEntity = (e) => { return(Guid.NewGuid()); }; Entity commercialOrderEntity = new Entity(); commercialOrderEntity.Id = Guid.NewGuid(); commercialOrderEntity.Attributes.Add(CommercialOrderEntity.Customer, new EntityReference("account", Guid.NewGuid())); commercialOrderEntity.Attributes.Add(CommercialOrderEntity.PriceList, new EntityReference("pricelevel", Guid.NewGuid())); commercialOrderEntity.Attributes.Add(CommercialOrderEntity.Currency, new EntityReference("transactioncurrencyid", Guid.NewGuid())); commercialOrderEntity.Attributes.Add(CommercialOrderEntity.BillingModel, new OptionSetValue(7464)); var selectedInstalledBaseLinesCount = 5; var selectedInstalledBaseLineEntities = TestDataCreator.GetSelectedInstalledBaseLineRecords(selectedInstalledBaseLinesCount); var newlyCreatedChangeOrderRecordGuids = PostChangeOrderDetailsCreate.CreateChangeOrderDetailsFromAvailableDetails(organizationService, tracingService, new Models.ChangeOrderDetailsCreationDetails() { NewlyCreatedChangeOrderDetailsRecord = changeOrderDetailsEntity, CommercialOrderRecord = commercialOrderEntity, SelectedInstalledBaseLineRecords = selectedInstalledBaseLineEntities }); Assert.AreEqual(selectedInstalledBaseLinesCount, newlyCreatedChangeOrderRecordGuids.Count); }
public void PostServiceRequestsmp_ReclassifyTestMethod() { var serviceProvider = new StubIServiceProvider(); var pluginContext = new StubIPluginExecutionContext(); var organizationService = new StubIOrganizationService(); pluginContext.PrimaryEntityNameGet = () => "incident"; pluginContext.PrimaryEntityIdGet = () => new Guid("884A078B-0467-E711-80F5-3863BB3C0660"); ParameterCollection paramCollection = new ParameterCollection(); Microsoft.Xrm.Sdk.ParameterCollection paramCollectionPostImage = new Microsoft.Xrm.Sdk.ParameterCollection(); Entity incident = new Entity("incident"); incident.Id = new Guid("884A078B-0467-E711-80F5-3863BB3C0660"); incident.Attributes["smp_incidentid"] = new EntityReference("incident", new Guid("884A078B-0467-E711-80F5-3863BB3C0660")); incident.Attributes["incidentid"] = new EntityReference("incident", new Guid("884A078B-0467-E711-80F5-3863BB3C0660")); incident.Attributes["customerid"] = new EntityReference("account", new Guid("884A078B-0469-E711-80F5-3863BB3C0560")); incident.Attributes["smp_createdfrom"] = new OptionSetValue(3); incident.Attributes["smp_referencesr"] = new EntityReference("incident", new Guid("884A078B-0467-E711-80F5-3863BB3C0660")); incident.Attributes["smp_flag"] = false; incident.Attributes["smp_problemoccureddatetime"] = "2018-01-08"; incident.Attributes["smp_portalsubmit"] = false; paramCollection.Add("Target", new EntityReference(incident.LogicalName, incident.Id)); pluginContext.InputParametersGet = () => paramCollection; pluginContext.OutputParametersGet = () => paramCollection; EntityImageCollection postImage = new EntityImageCollection { (new KeyValuePair <string, Entity>("PostImage", incident)) }; Helper.Helper.PluginVariables(serviceProvider, pluginContext, organizationService, 40, "smp_Reclassify", postImage); organizationService.RetrieveMultipleQueryBase = (query) => { EntityCollection collection = new EntityCollection(); string entityName = string.Empty; if (query.GetType().Name.Equals("FetchExpression")) { if (((FetchExpression)query).Query.Contains("<entity name='annotation'>")) { entityName = "annotation"; } } else if (query.GetType().Name.Equals("QueryExpression")) { entityName = ((QueryExpression)query).EntityName; } else { entityName = ((QueryByAttribute)query).EntityName; } if (entityName == "smp_servicerequestproblemtypedesc") { Entity servicerequestproblemtype = new Entity(entityName); servicerequestproblemtype.Id = Guid.NewGuid(); servicerequestproblemtype["smp_servicerequestproblemtypedescid"] = new EntityReference("smp_servicerequestproblemtypedesc", new Guid("884A078B-0466-E711-80F5-3863BB3C0560")); servicerequestproblemtype["smp_problemtypedescriptionid"] = new EntityReference("smp_problemtypedescription", new Guid("884A078B-0466-E711-80F5-3863BB3C0560")); servicerequestproblemtype["smp_answer"] = "Sample Answer"; servicerequestproblemtype["smp_servicerequestid"] = new EntityReference("incident", new Guid("884A078B-0466-E711-80F5-3863BB3C0560")); collection.Entities.Add(servicerequestproblemtype); } else if (entityName == "annotation") { Entity annotation = new Entity(entityName); annotation.Id = Guid.NewGuid(); annotation["annotationid"] = annotation.Id; annotation["subject"] = "Sample subject"; annotation["notetext"] = "Sample text"; annotation["filename"] = "Sample filename4"; annotation["isdocument"] = true; annotation["documentbody"] = "Sample body"; annotation["createdon"] = DateTime.Now.AddDays(-10); annotation["objectid"] = new EntityReference("incident", new Guid("884A078B-0467-E711-80F5-3863BB3C0660")); annotation["objecttypecode"] = "incident"; collection.Entities.Add(annotation); } else if (entityName == "account") { Entity account = new Entity(entityName); account.Id = new Guid("884A078B-0467-E711-80F5-3863BB3C0660"); account["accountid"] = new Guid("884A078B-0467-E711-80F5-3863BB3C0660"); account["name"] = "test"; account["smp_iscmmsintegrationenabled"] = true; account["smp_cmmsurl"] = "https://testurl/cmmsservicerequestmanagerAAD.svc"; account["smp_hostedonazure"] = false; account["smp_providerteam"] = new EntityReference("team", new Guid("884A078B-0467-E711-80F5-3863BB3C0652")); collection.Entities.Add(account); } return(collection); }; organizationService.RetrieveStringGuidColumnSet = delegate(string entity, Guid guid, ColumnSet secondaryUserColumnSet) { if (entity == "incident") { Entity incident2 = new Entity(entity); incident2.Id = new Guid("884A078B-0467-E711-80F5-3863BB3C0660"); incident2["incidentid"] = new EntityReference("incident", new Guid("884A078B-0467-E711-80F5-3863BB3C0660")); incident2["customerid"] = new EntityReference("account", new Guid("884A078B-0469-E711-80F5-3863BB3C0560")); incident2["smp_createdfrom"] = new OptionSetValue(3); incident2["smp_referencesr"] = new EntityReference("incident", new Guid("884A078B-0467-E711-80F5-3863BB3C0660")); incident2["smp_flag"] = false; incident2["smp_problemoccureddatetime"] = "2018-01-08"; incident2["smp_portalsubmit"] = false; return(incident2); } if (entity == "account") { Entity account = new Entity(entity); account.Id = new Guid("884A078B-0467-E711-80F5-3863BB3C0660"); account["name"] = "test"; account["smp_iscmmsintegrationenabled"] = true; account["smp_cmmsurl"] = "https://testurl/cmmsservicerequestmanagerAAD.svc"; account["smp_hostedonazure"] = false; account["smp_providerteam"] = new EntityReference("team", new Guid("884A078B-0467-E711-80F5-3863BB3C0652")); return(account); } return(null); }; Guid expected = new Guid("884A078B-0467-E711-80F5-3863BB3C0660"); Entity clonedEntity = null; organizationService.CreateEntity = e => { clonedEntity = e; return(expected); }; PostServiceRequestsmp_Reclassify reclassify = new PostServiceRequestsmp_Reclassify(); reclassify.Execute(serviceProvider); }
protected void dxgaugeTotals_CustomCallback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e) { try { ParameterCollection _params = new ParameterCollection(); string _query = ""; float[] _values = { 0, 0, 0, 0 }; //containers, weight, cube (cbm), pallets //*************** //21.10.2014 Paul Edwards for delivery tracking and container check which DeliveryID's are visible for this company //check individual contact ID iso string _contactid = ((UserClass)Page.Session["user"]).UserId.ToString(); IList <string> _deliveryids = null; _deliveryids = wwi_func.array_from_xml("xml\\contact_iso.xml", "contactlist/contact[id='" + _contactid + "']/deliveryids/deliveryid/value"); if (_deliveryids.Count > 0) { //don't use sql IN(n) as linq won't parse the statement string _deliveries = "(DeliveryAddress==" + string.Join(" OR DeliveryAddress==", _deliveryids.Select(i => i.ToString()).ToArray()) + ")"; _params.Add("NULL", _deliveries); //select for this company off list } //**************** string _f = ""; if (_params.Count > 0) { foreach (Parameter p in _params) { string _pname = p.Name.ToString(); string _op = "AND"; string[] _check = _pname.Split("_".ToCharArray()); _pname = _check[0].ToString(); _op = _check.Length > 1 ? _check[1].ToString() : _op; string _a = _f != "" ? " " + _op + " " : ""; _f += _pname != "NULL" ? _a + "(" + _pname + "==" + p.DefaultValue.ToString() + ")" : _a + "(" + p.DefaultValue.ToString() + ")"; } if (_query != "") { _query = _f + " AND " + _query; } else { _query = _f; } } //**************** //get starting ETS and ending ETS for current date //convert(datetime,'28/03/2013 10:32',103) //if no datetimes seelcted default to 0/01/1900 so no data displayed DateTime?_ets = DateTime.Now; //**************** //important! need a key id or error=key expression is undefined //e.KeyExpression = "ContainerIdx"; //10.11/2014 if necessary send to datatable then use datatable.compute method on clientname to summarise without showing //breakdown by delivery address if (!string.IsNullOrEmpty(_query)) { linq.linq_aggregate_containers_udfDataContext _ct = new linq.linq_aggregate_containers_udfDataContext(); IEnumerator <linq.aggregate_containers_by_etsResult> _in = _ct.aggregate_containers_by_ets(_ets, _ets).Where(_query).GetEnumerator(); while (_in.MoveNext()) { linq.aggregate_containers_by_etsResult _c = _in.Current; _values[0] += (float)_c.ContainerCount; _values[1] += (float)_c.SumWeight; _values[2] += (float)_c.SumCbm; _values[3] += (float)_c.SumPackages; } } //bind aggregates to guage for (int _ix = 0; _ix < _values.Length; _ix++) { ((LinearGauge)this.dxguageTotals.Gauges[_ix]).Scales[0].Value = _values[_ix]; } //end for } catch (Exception ex) { this.dxlblerr1.Text = ex.Message.ToString(); this.dxlblerr1.Visible = true; } }
public void AttachmentURLOnCreationTestMethodforWorkOrder() { using (ShimsContext.Create()) { AttachmentURLOnCreation attachmentURLOnCreate = new AttachmentURLOnCreation(); var serviceProvider = new StubIServiceProvider(); var pluginContext = new StubIPluginExecutionContext(); var organizationService = new StubIOrganizationService(); pluginContext.PrimaryEntityNameGet = () => "smp_attachmentsurl"; pluginContext.PrimaryEntityIdGet = () => new Guid("54D94FC2-52AD-E511-8158-1458D04DB4D1"); ParameterCollection paramCollection = new ParameterCollection(); Entity attachmentUrl = new Entity("smp_attachmentsurl"); attachmentUrl.Id = new Guid("54D94FC2-52AD-E511-8158-1458D04DB4D1"); attachmentUrl["smp_isdelete"] = false; attachmentUrl["smp_source"] = new OptionSetValue(Constants.SourceAX); attachmentUrl["smp_name"] = "testfile"; attachmentUrl["smp_objectid"] = "884A078B-0467-E711-80F5-3863BB3C0660"; attachmentUrl["smp_objecttypecode"] = "10266"; attachmentUrl["smp_mimetype"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; ////attachmentUrl["smp_bloburl"] = this.bloburl; paramCollection.Add("Target", attachmentUrl); pluginContext.InputParametersGet = () => paramCollection; PluginVariables(serviceProvider, pluginContext, organizationService, 40, "Create", null); organizationService.RetrieveMultipleQueryBase = (query) => { EntityCollection collection = new EntityCollection(); string entityName = string.Empty; if (query.GetType().Name.Equals("FetchExpression")) { if (((Microsoft.Xrm.Sdk.Query.FetchExpression)query).Query.Contains("<entity name='ava_keyvaluepair'>")) { entityName = "ava_keyvaluepair"; } } else if (query.GetType().Name.Equals("QueryExpression")) { entityName = ((QueryExpression)query).EntityName; } else { entityName = ((QueryByAttribute)query).EntityName; } if (entityName == "annotation") { Entity note = new Entity("annotation"); note.Id = new Guid("884A078B-0467-E711-80F5-3863BB3C0660"); note.Attributes["smp_name"] = "Test"; collection.Entities.Add(note); } return(collection); }; organizationService.RetrieveStringGuidColumnSet = delegate(string entity, Guid guid, ColumnSet secondaryUserColumnSet) { if (entity == "smp_attachmentsurl") { Entity attachmentUrlentity = new Entity("smp_attachmentsurl"); attachmentUrlentity.Id = new Guid("884A078B-0467-E711-80F5-3863BB3C0660"); attachmentUrlentity.Attributes["smp_objectid"] = "54D94FC2-52AD-E511-8158-1458D04DB4D1"; attachmentUrlentity.Attributes["smp_name"] = "Test"; attachmentUrlentity.Attributes["smp_source"] = new OptionSetValue(180620001); attachmentUrlentity.Attributes["smp_notesid"] = "884A078B-0467-E711-80F5-3863BB3C0660"; return(attachmentUrlentity); } if (entity == "annotation") { Entity note = new Entity("annotation"); note.Id = new Guid("884A078B-0467-E711-80F5-3863BB3C0660"); note.Attributes["smp_name"] = "Test"; return(note); } if (entity == "msdyn_workorder") { Entity workorder = new Entity { LogicalName = "msdyn_workorder", Id = new Guid("884A078B-0467-E711-80F5-3863BB3C0680") }; return(workorder); } return(null); }; attachmentURLOnCreate.Execute(serviceProvider); } }
private void Initialize() { JToken mockOptionsResourceObject = JToken.Parse(_testFixtureAssembly.ReadEmbeddedResourceAsString(_mockResourceName)); MockOptionsResource = mockOptionsResourceObject.ToObject <TOptionsResource>(); Store = new List <Entity>(); Relationships = new List <MockRelationship>(); AssociateRequests = new List <AssociateRequest>(); if (!String.IsNullOrEmpty(MockOptionsResource.ProxyType)) { Type proxyType = Type.GetType(MockOptionsResource.ProxyType, true); ProxyTypesAssembly = proxyType.Assembly; } PrimaryEntityName = MockOptionsResource.PrimaryEntityName; Message = MockOptionsResource.Message; UserId = MockOptionsResource.UserId; InputParameters = new ParameterCollection(); foreach (MockParameter inputParameter in MockOptionsResource.InputParameters) { object parameterValue = null; if (inputParameter.Value is JObject inputeParameterValueJObject) { switch (inputParameter.Type) { case "Entity": parameterValue = (Entity)inputeParameterValueJObject.ToObject <MockEntity>(); break; case "EntityReference": parameterValue = (EntityReference)inputeParameterValueJObject.ToObject <MockEntityReference>(); break; default: parameterValue = inputeParameterValueJObject.ToObject <object>(); break; } } else { switch (inputParameter.Type) { case "Guid": parameterValue = Guid.Parse(inputParameter.Value.ToString()); break; default: parameterValue = inputParameter.Value; break; } } InputParameters.Add(inputParameter.Name, parameterValue); } LoadMockStore(MockOptionsResource.Store); LoadMockResource(); }
public bool ChangeProductSaleStatus(string productCategoryId, string productId, string statusName) { bool result = false; ProductCategoryDomainModel category = GetProductCategoryDomainModelById(productCategoryId); if (category == null) { return(false); } ProductInfoDomainModel product = GetProductDomainInfoByProductId(productId, false); if (product == null) { return(false); } if (product.BasicInfo.SalesStatus == statusName) { return(true); } product.BasicInfo.SalesStatus = statusName; //product.AttributeList[""] = statusName; try { BeginTransaction(); if (ProductInfoService.Instance.Update(product.BasicInfo) != 1) { RollbackTransaction(); return(false); } string sql = string.Format(@" UPDATE [{0}] SET [销售状态] = $statusName$, [modified_on] = GETDATE(), [modified_by] = $modifiedBy$ WHERE product_id = $productId$", category.BasicInfo.TableName); ParameterCollection pc = new ParameterCollection(); pc.Add("statusName", statusName); pc.Add("modifiedBy", SessionUtil.Current.UserId); pc.Add("productId", product.BasicInfo.ProductId); if (DbUtil.IBPDBManager.IData.ExecuteNonQuery(sql, pc) == 0) { RollbackTransaction(); return(false); } CommitTransaction(); GetProductDomainInfoByProductId(product.BasicInfo.ProductId, true); result = true; } catch (Exception ex) { RollbackTransaction(); LogUtil.Error(ex.Message, ex); throw ex; } return(result); }
protected void btnsubmit_Click(object sender, EventArgs e) { try { string testname = string.Empty; string testype = string.Empty; string totalquestions = string.Empty; string totalmarks = string.Empty; string testduration = string.Empty; string testdescription = string.Empty; string userid = Session["userid"].ToString(); if (ddltesttype.SelectedIndex > 0) { testype = ddltesttype.SelectedValue.ToString(); } else { ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "ErrorShow('Please Select Test Type');", true); return; } if (txttestname.Text.Trim() == "") { ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "ErrorShow('Provide Test Name');", true); return; } testname = txttestname.Text.Trim(); if (txttotalquestions.Text.Trim() == "") { ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "ErrorShow('Provide Total Questions In Test');", true); return; } totalquestions = txttotalquestions.Text.Trim(); if (txttotalmarks.Text.Trim() == "") { ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "ErrorShow('Provide Total Marks Of Test');", true); return; } totalmarks = txttotalmarks.Text.Trim(); if (txttestduration.Text.Trim() == "") { ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "ErrorShow('Provide Test Duration in Minutes');", true); return; } testduration = txttestduration.Text.Trim(); if (txtdescription.Text.Trim() == "") { ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "ErrorShow('Provide Test Description ');", true); return; } testdescription = txtdescription.Text.Trim(); ParameterCollection obParam = new ParameterCollection(); obParam.Add("@testname", testname); obParam.Add("@testdescription", testdescription); obParam.Add("@testtype", testype); obParam.Add("@totalquestions", totalquestions); obParam.Add("@testduration", testduration); obParam.Add("@totalmarks", totalmarks); Boolean result = dal.fnExecuteNonQueryByPro("CreateTest", obParam); if (result) { ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "SuccessMsg('Test Successfully Created');", true); txtdescription.Text = ""; txttestduration.Text = ""; txttestname.Text = ""; txttotalmarks.Text = ""; txttotalquestions.Text = ""; bindtableTest(testype); } else { ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "ErrorShow('Error in creation of test');", true); } } catch (Exception ex) { ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "ErrorShow('" + ex.Message + "');", true); } }
public List <string> GetProductList(string productCategoryId, Dictionary <string, QueryItemDomainModel> queryCollection, int pageIndex, int pageSize, string orderField, string orderDirection, out int total) { List <string> result = new List <string>(); total = 0; ProductCategoryInfoModel catInfo = ProductCategoryInfoService.Instance.GetProductCategoryInfoById(productCategoryId); if (catInfo == null) { Exception ex = new Exception("获取产品列表方法异常, 不存在的产品类型ID"); LogUtil.Error("获取产品列表方法异常, 不存在的产品类型ID", ex); throw ex; } Dictionary <string, ProductCategoryAttributesModel> attList = ProductCategoryAttributesService.Instance.GetProductCategoryAttributeList(productCategoryId, false); if (attList == null) { Exception ex = new Exception("获取产品列表方法异常, 不存在的产品类型ID"); LogUtil.Error("获取产品列表方法异常, 不存在的产品类型ID", ex); throw ex; } StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.AppendFormat(@"FROM [{0}] WHERE 1=1 ", catInfo.TableName); ParameterCollection pc = new ParameterCollection(); int count = 0; foreach (KeyValuePair <string, QueryItemDomainModel> item in queryCollection) { switch (item.Value.Operation) { case "equal": sqlBuilder.AppendFormat(@" AND [{0}] = $value{1}$", attList[item.Key].AttributeName, count); pc.Add("value" + count.ToString(), item.Value.SearchValue); break; case "notequal": sqlBuilder.AppendFormat(@" AND [{0}] <> $value{1}$", attList[item.Key].AttributeName, count); pc.Add("value" + count.ToString(), item.Value.SearchValue); break; case "contain": sqlBuilder.AppendFormat(@" AND [{0}] LIKE $value{1}$", attList[item.Key].AttributeName, count); pc.Add("value" + count.ToString(), "%" + item.Value.SearchValue + "%"); break; case "greater": sqlBuilder.AppendFormat(@" AND [{0}] > $value{1}$", attList[item.Key].AttributeName, count); pc.Add("value" + count.ToString(), item.Value.SearchValue); break; case "greaterequal": sqlBuilder.AppendFormat(@" AND [{0}] >= $value{1}$", attList[item.Key].AttributeName, count); pc.Add("value" + count.ToString(), item.Value.SearchValue); break; case "less": sqlBuilder.AppendFormat(@" AND [{0}] < $value{1}$", attList[item.Key].AttributeName, count); pc.Add("value" + count.ToString(), item.Value.SearchValue); break; case "lessequal": sqlBuilder.AppendFormat(@" AND [{0}] <= $value{1}$", attList[item.Key].AttributeName, count); pc.Add("value" + count.ToString(), item.Value.SearchValue); break; case "between": sqlBuilder.AppendFormat(@" AND [{0}] BETWEEN $begin{1}$ AND $end{1}$", attList[item.Key].AttributeName, count); pc.Add("begin" + count.ToString(), item.Value.BeginTime); pc.Add("end" + count.ToString(), item.Value.EndTime); break; case "today": sqlBuilder.AppendFormat(@" AND DATEDIFF(DAY,[{0}],GETDATE()) = 0", attList[item.Key].AttributeName); break; case "week": sqlBuilder.AppendFormat(@" AND DATEDIFF(WEEK,[{0}],GETDATE()) = 0", attList[item.Key].AttributeName); break; case "month": sqlBuilder.AppendFormat(@" AND DATEDIFF(MONTH,[{0}],GETDATE()) = 0", attList[item.Key].AttributeName); break; case "quarter": sqlBuilder.AppendFormat(@" AND DATEDIFF(QUARTER,[{0}],GETDATE()) = 0", attList[item.Key].AttributeName); break; case "year": sqlBuilder.AppendFormat(@" AND DATEDIFF(YEAR,[{0}],GETDATE()) = 0", attList[item.Key].AttributeName); break; default: break; } count++; } string totalSql = string.Format(@"SELECT COUNT(1) {0} ", sqlBuilder.ToString()); total = Convert.ToInt32(ExecuteScalar(totalSql, pc)); DataTable dt = ExecuteDataTable("SELECT product_id " + sqlBuilder.ToString(), pc, pageIndex, pageSize, OrderByCollection.Create(orderField, orderDirection)); if (dt != null && dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { result.Add(dt.Rows[i][0].ToString()); } } return(result); }
public void TestMethod1() { var serviceProviderMock = new Mock <IServiceProvider>(); var traceServiceMock = new Mock <ITracingService>(); //Plugin Context var pluginContextMock = new Mock <IPluginExecutionContext>(); //pluginContextMock.Setup(c => c.UserId).Returns(new Guid()); //Target InputParameter for plugin context var parameterCollection = new ParameterCollection(); parameterCollection.Add("Target", new Account() { Id = Guid.NewGuid() }); pluginContextMock.Setup(c => c.InputParameters).Returns(parameterCollection); //Organisation Service var organisationServiceMock = new Mock <IOrganizationService>(); var entityCollection = new EntityCollection(); entityCollection.Entities.Add(new Email() { Id = Guid.NewGuid(), Subject = "Mock 1" }); entityCollection.Entities.Add(new Email() { Id = Guid.NewGuid(), Subject = "Mock 2" }); entityCollection.Entities.Add(new Email() { Id = Guid.NewGuid() }); organisationServiceMock.Setup(s => s.RetrieveMultiple(It.IsAny <QueryBase>())).Returns(entityCollection); //Factory var organisationServicefactoryMock = new Mock <IOrganizationServiceFactory>(); organisationServicefactoryMock.Setup(f => f.CreateOrganizationService(It.IsAny <Guid>())).Returns(organisationServiceMock.Object); //Set up provider mothods serviceProviderMock.Setup(sp => sp.GetService(typeof(ITracingService))).Returns(traceServiceMock.Object); serviceProviderMock.Setup(sp => sp.GetService(typeof(IPluginExecutionContext))).Returns(pluginContextMock.Object); serviceProviderMock.Setup(sp => sp.GetService(typeof(IOrganizationServiceFactory))).Returns(organisationServicefactoryMock.Object); var plugin = new UpdateActivitiesRefactored(); plugin.Execute(serviceProviderMock.Object); //var iserviceProvider = new IServiceProvider(); //plugin.Execute(); //Context validation organisationServiceMock.Verify(dal => dal.Execute(It.IsAny <SetStateRequest>()), Times.Exactly(1)); organisationServiceMock.Verify(dal => dal.Update(It.IsAny <Entity>()), Times.Exactly(2)); traceServiceMock.Verify(trace => trace.Trace("{0} closed emails and {1} updated emails", 1, 2), Times.Exactly(1)); }
public override void RefreshSchema(bool preferSilent) { try { this.SuppressDataSourceEvents(); bool flag = false; IServiceProvider site = this.SqlDataSource.Site; if (!this.CanRefreshSchema) { if (!preferSilent) { UIServiceHelper.ShowError(site, System.Design.SR.GetString("SqlDataSourceDesigner_RefreshSchemaRequiresSettings")); } } else { IDataSourceViewSchema schema = this.GetView("DefaultView").Schema; bool flag2 = false; if (schema == null) { this._forceSchemaRetrieval = true; schema = this.GetView("DefaultView").Schema; this._forceSchemaRetrieval = false; flag2 = true; } DesignerDataConnection connection = new DesignerDataConnection(string.Empty, this.ProviderName, this.ConnectionString); if (preferSilent) { flag = this.RefreshSchema(connection, this.SelectCommand, this.SqlDataSource.SelectCommandType, this.SqlDataSource.SelectParameters, true); } else { Parameter[] parameterArray = this.InferParameterNames(connection, this.SelectCommand, this.SqlDataSource.SelectCommandType); if (parameterArray == null) { return; } ParameterCollection parameters = new ParameterCollection(); ParameterCollection parameters2 = new ParameterCollection(); foreach (ICloneable cloneable in this.SqlDataSource.SelectParameters) { parameters2.Add((Parameter)cloneable.Clone()); } foreach (Parameter parameter in parameterArray) { if ((parameter.Direction == ParameterDirection.Input) || (parameter.Direction == ParameterDirection.InputOutput)) { Parameter parameter2 = parameters2[parameter.Name]; if (parameter2 != null) { parameter.DefaultValue = parameter2.DefaultValue; if ((parameter.DbType == DbType.Object) && (parameter.Type == TypeCode.Empty)) { parameter.DbType = parameter2.DbType; parameter.Type = parameter2.Type; } parameters2.Remove(parameter2); } parameters.Add(parameter); } } if (parameters.Count > 0) { SqlDataSourceRefreshSchemaForm form = new SqlDataSourceRefreshSchemaForm(site, this, parameters); flag = UIServiceHelper.ShowDialog(site, form) == DialogResult.OK; } else { flag = this.RefreshSchema(connection, this.SelectCommand, this.SqlDataSource.SelectCommandType, parameters, false); } } if (flag) { IDataSourceViewSchema schema2 = this.GetView("DefaultView").Schema; if (flag2 && DataSourceDesigner.ViewSchemasEquivalent(schema, schema2)) { this.OnDataSourceChanged(EventArgs.Empty); } else if (!DataSourceDesigner.ViewSchemasEquivalent(schema, schema2)) { this.OnSchemaRefreshed(EventArgs.Empty); } } } } finally { this.ResumeDataSourceEvents(); } }
private void OnTestQueryButtonClick(object sender, EventArgs e) { ParameterCollection parameters = new ParameterCollection(); foreach (Parameter parameter in this._selectQuery.Parameters) { if (parameter.DbType == DbType.Object) { parameters.Add(new Parameter(parameter.Name, parameter.Type, parameter.DefaultValue)); } else { parameters.Add(new Parameter(parameter.Name, parameter.DbType, parameter.DefaultValue)); } } if (parameters.Count > 0) { SqlDataSourceParameterValueEditorForm form = new SqlDataSourceParameterValueEditorForm(base.ServiceProvider, parameters); if (UIServiceHelper.ShowDialog(base.ServiceProvider, form) == DialogResult.Cancel) { return; } } this._resultsGridView.DataSource = null; DbCommand command = null; Cursor current = Cursor.Current; try { Cursor.Current = Cursors.WaitCursor; DbProviderFactory dbProviderFactory = SqlDataSourceDesigner.GetDbProviderFactory(this._dataConnection.ProviderName); DbConnection designTimeConnection = null; try { designTimeConnection = SqlDataSourceDesigner.GetDesignTimeConnection(base.ServiceProvider, this._dataConnection); } catch (Exception exception) { if (designTimeConnection == null) { UIServiceHelper.ShowError(base.ServiceProvider, exception, System.Design.SR.GetString("SqlDataSourceSummaryPanel_CouldNotCreateConnection")); return; } } if (designTimeConnection == null) { UIServiceHelper.ShowError(base.ServiceProvider, System.Design.SR.GetString("SqlDataSourceSummaryPanel_CouldNotCreateConnection")); } else { command = this._sqlDataSourceDesigner.BuildSelectCommand(dbProviderFactory, designTimeConnection, this._selectQuery.Command, parameters, this._selectQuery.CommandType); DbDataAdapter adapter = SqlDataSourceDesigner.CreateDataAdapter(dbProviderFactory, command); adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey; DataSet dataSet = new DataSet(); adapter.Fill(dataSet); if (dataSet.Tables.Count == 0) { UIServiceHelper.ShowError(base.ServiceProvider, System.Design.SR.GetString("SqlDataSourceSummaryPanel_CannotExecuteQueryNoTables")); } else { this._resultsGridView.DataSource = dataSet.Tables[0]; foreach (DataGridViewColumn column in this._resultsGridView.Columns) { column.SortMode = DataGridViewColumnSortMode.NotSortable; } this._resultsGridView.AutoResizeColumnHeadersHeight(); this._resultsGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells); } } } catch (Exception exception2) { UIServiceHelper.ShowError(base.ServiceProvider, exception2, System.Design.SR.GetString("SqlDataSourceSummaryPanel_CannotExecuteQuery")); } finally { if ((command != null) && (command.Connection.State == ConnectionState.Open)) { command.Connection.Close(); } Cursor.Current = current; } }
public override void ExportToParameters(ParameterCollection p) { if (p == null) { throw new ArgumentNullException(nameof(p)); } base.ExportToParameters(p); p.Add("STYLE", Style); { var(n, f) = Utils.CoordToDxpFrac(Location.X); if (n != 0 || f != 0) { p.Add("LOCATION.X", n); } if (f != 0) { p.Add("LOCATION.X" + "_FRAC", f); } } { var(n, f) = Utils.CoordToDxpFrac(Location.Y); if (n != 0 || f != 0) { p.Add("LOCATION.Y", n); } if (f != 0) { p.Add("LOCATION.Y" + "_FRAC", f); } } p.Add("COLOR", Color); p.Add("ORIENTATION", (int)Orientation); p.Add("FONTID", FontId); p.Add("TEXT", Text); p.Add("SHOWNETNAME", ShowNetName); p.Add("ISCROSSSHEETCONNECTOR", IsCrossSheetConnector); }
public override void ExportToParameters(ParameterCollection p) { if (p == null) { throw new ArgumentNullException(nameof(p)); } base.ExportToParameters(p); p.Add("LIBREFERENCE", LibReference); p.Add("COMPONENTDESCRIPTION", ComponentDescription); p.Add("PARTCOUNT", PartCount + 1); p.Add("DISPLAYMODECOUNT", DisplayModeCount); p.Add("LIBRARYPATH", LibraryPath); p.Add("SOURCELIBRARYNAME", SourceLibraryName); p.Add("SHEETPARTFILENAME", SheetPartFilename); p.Add("TARGETFILENAME", TargetFilename); p.Add("AREACOLOR", AreaColor); p.Add("COLOR", Color); p.Add("PARTIDLOCKED", PartIdLocked); p.Add("ALIASLIST", AliasList); }
public void PostUpdateofNoteIdAttachmentURLTestMethod() { using (ShimsContext.Create()) { PostUpdateofNoteIdAttachmentURL attachmentURLOnUpdate = new PostUpdateofNoteIdAttachmentURL(); var serviceProvider = new StubIServiceProvider(); var pluginContext = new StubIPluginExecutionContext(); var organizationService = new StubIOrganizationService(); pluginContext.PrimaryEntityNameGet = () => "smp_attachmentsurl"; pluginContext.PrimaryEntityIdGet = () => new Guid("54D94FC2-52AD-E511-8158-1458D04DB4D1"); ParameterCollection paramCollection = new ParameterCollection(); Entity attachmentUrl = new Entity("smp_attachmentsurl"); attachmentUrl.Id = new Guid("54D94FC2-52AD-E511-8158-1458D04DB4D1"); attachmentUrl["smp_isdelete"] = true; attachmentUrl["smp_notesid"] = "884A078B-0467-E711-80F5-3863BB3C0660"; attachmentUrl["smp_source"] = new OptionSetValue(180620000); paramCollection.Add("Target", attachmentUrl); pluginContext.InputParametersGet = () => paramCollection; PluginVariables(serviceProvider, pluginContext, organizationService, 40, "Update", null); organizationService.RetrieveMultipleQueryBase = (query) => { EntityCollection collection = new EntityCollection(); string entityName = string.Empty; if (query.GetType().Name.Equals("FetchExpression")) { if (((Microsoft.Xrm.Sdk.Query.FetchExpression)query).Query.Contains("<entity name='ava_keyvaluepair'>")) { entityName = "ava_keyvaluepair"; } } else if (query.GetType().Name.Equals("QueryExpression")) { entityName = ((QueryExpression)query).EntityName; } else { entityName = ((QueryByAttribute)query).EntityName; } if (entityName == "smp_attachmentsurl") { Entity attachmentUrlentity = new Entity("smp_attachmentsurl"); attachmentUrlentity.Id = new Guid("884A078B-0467-E711-80F5-3863BB3C0660"); attachmentUrlentity.Attributes["smp_objectid"] = "54D94FC2-52AD-E511-8158-1458D04DB4D1"; attachmentUrlentity.Attributes["smp_name"] = "Test"; attachmentUrlentity.Attributes["smp_source"] = new OptionSetValue(180620000); attachmentUrlentity.Attributes["smp_notesid"] = "884A078B-0467-E711-80F5-3863BB3C0660"; collection.Entities.Add(attachmentUrlentity); } return(collection); }; organizationService.RetrieveStringGuidColumnSet = delegate(string entity, Guid guid, ColumnSet secondaryUserColumnSet) { if (entity == "smp_attachmentsurl") { Entity attachmentUrlentity = new Entity("smp_attachmentsurl"); attachmentUrlentity.Id = new Guid("884A078B-0467-E711-80F5-3863BB3C0660"); attachmentUrlentity.Attributes["smp_objectid"] = "54D94FC2-52AD-E511-8158-1458D04DB4D1"; attachmentUrlentity.Attributes["smp_name"] = "Test"; attachmentUrlentity.Attributes["smp_source"] = new OptionSetValue(180620000); attachmentUrlentity.Attributes["smp_notesid"] = "884A078B-0467-E711-80F5-3863BB3C0660"; return(attachmentUrlentity); } return(null); }; attachmentURLOnUpdate.Execute(serviceProvider); } }
public override void ExportToParameters(ParameterCollection p) { if (p == null) { throw new ArgumentNullException(nameof(p)); } base.ExportToParameters(p); { var(n, f) = Utils.CoordToDxpFrac(Location.X); if (n != 0 || f != 0) { p.Add("LOCATION.X", n); } if (f != 0) { p.Add("LOCATION.X" + "_FRAC", f); } } { var(n, f) = Utils.CoordToDxpFrac(Location.Y); if (n != 0 || f != 0) { p.Add("LOCATION.Y", n); } if (f != 0) { p.Add("LOCATION.Y" + "_FRAC", f); } } { var(n, f) = Utils.CoordToDxpFrac(Corner.X); if (n != 0 || f != 0) { p.Add("CORNER.X", n); } if (f != 0) { p.Add("CORNER.X" + "_FRAC", f); } } { var(n, f) = Utils.CoordToDxpFrac(Corner.Y); if (n != 0 || f != 0) { p.Add("CORNER.Y", n); } if (f != 0) { p.Add("CORNER.Y" + "_FRAC", f); } } p.Add("CORNERXRADIUS", CornerXRadius); p.Add("CORNERYRADIUS", CornerYRadius); p.Add("LINEWIDTH", (int)LineWidth); p.Add("COLOR", Color); p.Add("AREACOLOR", AreaColor); p.Add("ISSOLID", IsSolid); }
public DataTable GetDataTable(bool isCreatedBy, SalesOrderStatus orderStatus, string incomePhoneNumber, string selectedPhoneNumber, Dictionary <string, QueryItemDomainModel> queryCollection) { #region MyRegion DataTable dt = new DataTable(); StringBuilder sqlBuilder = new StringBuilder(); ParameterCollection pc = new ParameterCollection(); sqlBuilder.Append(@" customer_basic_info.created_on as customer_create_on,pay_card_number,pay_card_period,pay_card_securitycode ,order_source=(SELECT data_value FROM custom_data_value WHERE value_id=order_source),pay_card_bank_id=(SELECT data_value FROM custom_data_value where value_id=pay_card_bank_id) ,opening_time,collection_card_number,collection_customer_name,mobile_phone,home_phone,other_phone ,collection_bank_id =(SELECT data_value FROM custom_data_value where value_id=package.collection_bank_id) ,package.idcard_number,package.owner_customer_name,charge_user_id=(select created_user_info.cn_name from user_info where user_id=charge_user_id) ,recover_time,sign_time,salesorder_basic_info.remark,need_invoice= case when pay_type='0' then '是' when pay_type='1' then '否' end ,delivery_address,delivery_receive_phonenumber,delivery_receive_customer_name,charge_time, package.bind_main_phonenumber ,package.bind_subsidiary_phonenumber,category_name, sex= case when pay_type='0' then '男' when pay_type='1' then '女' end ,salesorder_basic_info.delivery_time,salesorder_basic_info.approval_time,salesorder_basic_info.salesorder_code, customer_basic_info.customer_name ,custom_data_value.data_value,salesorder_basic_info.pay_price,pay_type= case when pay_type='0' then '分期' when pay_type='1' then '全额' when pay_type='2' then '到付' when pay_type='3' then '在线支付' end ,created_user_info.cn_name,salesorder_basic_info.created_on FROM salesorder_basic_info LEFT JOIN customer_basic_info ON salesorder_basic_info.customer_id = customer_basic_info.customer_id LEFT JOIN custom_data_value ON salesorder_basic_info.pay_idcard_type_id=custom_data_value.value_id LEFT JOIN user_info as created_user_info ON salesorder_basic_info.created_by = created_user_info.user_id LEFT JOIN salesorder_communiationpackage_info as package ON salesorder_basic_info.salesorder_id = package.salesorder_id LEFT JOIN product_category_info as product ON package.bind_communiationpackage_id = product.product_category_id WHERE 1 = 1 "); if (orderStatus != SalesOrderStatus.All) { if (orderStatus == SalesOrderStatus.Exception) { sqlBuilder.Append(@" AND is_exception = 0 "); } else { sqlBuilder.Append(@" AND now_order_status_id = $orderStatus$ and is_exception<>0"); pc.Add("orderStatus", Convert.ToInt32(orderStatus)); } } #region 根据用户名查询 if (isCreatedBy == true) { sqlBuilder.Append(@" AND salesorder_basic_info.created_by = $created_by$ "); pc.Add("created_by", SessionUtil.Current.UserId); } #endregion #region 所选号码查询条件 if (!string.IsNullOrEmpty(selectedPhoneNumber)) { sqlBuilder.Append(@" AND salesorder_basic_info.salesorder_id IN (SELECT salesorder_basic_info.salesorder_id FROM salesorder_communiationpackage_info WHERE bind_main_phonenumber = $selectedPhoneNumber$ or bind_subsidiary_phonenumber = $selectedPhoneNumber$ ) "); pc.Add("selectedPhoneNumber", selectedPhoneNumber); } #endregion #region 来电号码查询条件 if (string.IsNullOrEmpty(incomePhoneNumber) == false) { sqlBuilder.Append(@" AND customer_basic_info.customer_id IN (SELECT customer_basic_info.customer_id FROM customer_phone_info WHERE phone_number LIKE $incomePhoneNumber$)"); pc.Add("incomePhoneNumber", string.Format("%{0}%", incomePhoneNumber)); } #endregion #region 构造查询条件 int count = 0; foreach (QueryItemDomainModel item in queryCollection.Values) { switch (item.Operation) { case "equal": sqlBuilder.AppendFormat(@" AND {0} = $value{1}$", item.FieldType, count); pc.Add("value" + count.ToString(), item.SearchValue); break; case "notequal": sqlBuilder.AppendFormat(@" AND {0} <> $value{1}$", item.FieldType, count); pc.Add("value" + count.ToString(), item.SearchValue); break; case "contain": sqlBuilder.AppendFormat(@" AND {0} LIKE $value{1}$", item.FieldType, count); pc.Add("value" + count.ToString(), "%" + item.SearchValue + "%"); break; case "greater": sqlBuilder.AppendFormat(@" AND {0} > $value{1}$", item.FieldType, count); pc.Add("value" + count.ToString(), item.SearchValue); break; case "greaterequal": sqlBuilder.AppendFormat(@" AND {0} >= $value{1}$", item.FieldType, count); pc.Add("value" + count.ToString(), item.SearchValue); break; case "less": sqlBuilder.AppendFormat(@" AND {0} < $value{1}$", item.FieldType, count); pc.Add("value" + count.ToString(), item.SearchValue); break; case "lessequal": sqlBuilder.AppendFormat(@" AND {0} <= $value{1}$", item.FieldType, count); pc.Add("value" + count.ToString(), item.SearchValue); break; case "between": sqlBuilder.AppendFormat(@" AND {0} BETWEEN $begin{1}$ AND $end{1}$", item.FieldType, count); pc.Add("begin" + count.ToString(), item.BeginTime); pc.Add("end" + count.ToString(), item.EndTime); break; case "today": sqlBuilder.AppendFormat(@" AND DATEDIFF(DAY,{0},GETDATE()) = 0", item.FieldType); break; case "week": sqlBuilder.AppendFormat(@" AND DATEDIFF(WEEK,{0},GETDATE()) = 0", item.FieldType); break; case "month": sqlBuilder.AppendFormat(@" AND DATEDIFF(MONTH,{0},GETDATE()) = 0", item.FieldType); break; case "quarter": sqlBuilder.AppendFormat(@" AND DATEDIFF(QUARTER,{0},GETDATE()) = 0", item.FieldType); break; case "year": sqlBuilder.AppendFormat(@" AND DATEDIFF(YEAR,{0},GETDATE()) = 0", item.FieldType); break; default: break; } count++; } #endregion dt = ExecuteDataTable("SELECT " + sqlBuilder.ToString(), pc); return(dt); #endregion }
/// <summary> /// 删除产品类型信息。 /// </summary> /// <param name="categoryId"></param> /// <param name="message"></param> /// <returns></returns> public bool DeleteProductCategory(string categoryId, out string message) { bool result = false; message = "操作失败,请与管理员联系"; if (string.IsNullOrEmpty(categoryId)) { message = "缺少参数,请与管理员联系"; return(false); } Dictionary <string, ProductCategoryInfoModel> dict = GetProductCategoryList(false); if (dict.ContainsKey(categoryId) == false) { message = "操作失败,产品类型ID不存在"; return(false); } ProductCategoryInfoModel oldCatInfo = dict[categoryId]; try { BeginTransaction(); string deleteCategoryAttributeSQL = "DELETE FROM product_category_attributes WHERE product_category_id = $categoryId$;"; string deleteCategorySaleStatusSQL = "DELETE FROM product_category_sales_status WHERE product_category_id = $categoryId$;"; string deleteCategoryAttributeValueSQL = "DELETE FROM product_attributes_value WHERE product_category_id = $categoryId$;"; ParameterCollection pc = new ParameterCollection(); pc.Add("categoryId", categoryId); if (Delete(categoryId) == 1) { ExecuteNonQuery(deleteCategoryAttributeSQL, pc); ExecuteNonQuery(deleteCategorySaleStatusSQL, pc); ExecuteNonQuery(deleteCategoryAttributeValueSQL, pc); string dropTableSQL = DTableUtil.GetDropTableSQL(oldCatInfo.TableName); ExecuteNonQuery(dropTableSQL); foreach (ProductCategoryInfoModel item in dict.Values) { if (item.SortOrder > oldCatInfo.SortOrder) { item.SortOrder -= 1; if (Update(item) != 1) { RollbackTransaction(); message = "重构产品类型信息排序索引失败"; result = false; } } } CommitTransaction(); ProductCategoryAttributesService.Instance.GetProductCategoryAttributeList(categoryId, true); ProductCategoryAttributesService.Instance.GetProductCategoryAttributeGroupList(categoryId, true); ProductCategorySalesStatusService.Instance.GetProductCategorySalesStatusList(categoryId, true); GetProductCategoryList(true); message = "成功删除产品类型信息"; result = true; } else { RollbackTransaction(); message = "删除产品类型信息失败"; result = false; } } catch (Exception ex) { RollbackTransaction(); LogUtil.Error("删除产品类型信息异常", ex); throw ex; } return(result); }
protected void Page_Load(object sender, EventArgs e) { if (Session["userid"] != null) { if (Session["TestDetails"] != null) { DataTable dtanswerskeys = new DataTable(); //Add Columns to datatable dtanswerskeys.Columns.Add("QuestionNo", typeof(Int32)); dtanswerskeys.Columns.Add("Attempted", typeof(string)); dtanswerskeys.Columns.Add("Correct", typeof(string)); divtable.InnerHtml = ""; StringBuilder htmlTable = new StringBuilder(); DataTable dt = (DataTable)Session["TestDetails"]; if (dt.Rows.Count > 0) { htmlTable.Append(""); htmlTable.Append("<table class='table table-xs mb-0' > "); htmlTable.Append("<tr>"); htmlTable.Append("<td><b>Question No.</b></td> <td> <b>Attempted Option</b></td> <td><b>Correct Option</b></td>"); htmlTable.Append("</tr>"); int TotalQuestions = dt.Rows.Count; int CorrectAnsCount = 0; int AttemptedQuestionsCount = 0; for (int i = 0; i < dt.Rows.Count; i++) { string QuestionNo = string.Empty; string Attemptedoption = string.Empty; string CorrectOption = string.Empty; QuestionNo = dt.Rows[i]["Row_Number"].ToString(); ParameterCollection obParam = new ParameterCollection(); obParam.Add("@qid", dt.Rows[i]["qid"].ToString()); obDs = dal.fnRetriveByPro("GetAnwersByQidforScore", obParam); if (obDs.Tables.Count > 0) { if (obDs.Tables[0].Rows.Count > 0) { for (int j = 0; j < obDs.Tables[0].Rows.Count; j++) { if (Convert.ToInt32(obDs.Tables[0].Rows[j]["ansid"]) == Convert.ToInt32(dt.Rows[i]["CorrectAnsid"])) { CorrectOption = obDs.Tables[0].Rows[j]["ansdescription"].ToString(); } if (Convert.ToInt32(dt.Rows[i]["Ansid"]) != 0) { if (Convert.ToInt32(obDs.Tables[0].Rows[j]["ansid"]) == Convert.ToInt32(dt.Rows[i]["Ansid"])) { Attemptedoption = obDs.Tables[0].Rows[j]["ansdescription"].ToString(); } } else { Attemptedoption = "Not Attempted"; } } } } if (dt.Rows[i]["Ansid"].ToString() == dt.Rows[i]["CorrectAnsid"].ToString()) { CorrectAnsCount = CorrectAnsCount + 1; } if (Convert.ToBoolean(dt.Rows[i]["IsAttempted"])) { AttemptedQuestionsCount = AttemptedQuestionsCount + 1; } dtanswerskeys.Rows.Add(Convert.ToInt32(QuestionNo), Attemptedoption, CorrectOption); htmlTable.Append("<tr>"); htmlTable.Append("<td>" + QuestionNo + "</td> <td> " + Attemptedoption + " </td> <td> " + CorrectOption + " </td>"); htmlTable.Append("</tr>"); } Session["dtanwerkeys"] = dtanswerskeys; dal.fnExecuteNonQuery("insert into MyScoreCard ([Userid],[Testid],[TotalQuestions],[TotalAttempted],[TotalCorrected]) values ('" + dt.Rows[0]["Userid"].ToString() + "','" + dt.Rows[0]["Testid"].ToString() + "','" + TotalQuestions.ToString() + "','" + AttemptedQuestionsCount.ToString() + "','" + CorrectAnsCount.ToString() + "')"); //lblrightquestions.Text = "Total Questions: " + TotalQuestions + " Attempted : " + AttemptedQuestionsCount + " Correct Questions :" + CorrectAnsCount; htmlTable.Append("</table>"); divtable.InnerHtml = htmlTable.ToString(); ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "ResultPopup();", true); } Session["TestDetails"] = null; } string userid = Session["userid"].ToString().ToUpper(); string username = Session["username"].ToString().ToUpper(); if (!IsPostBack) { BindAllTestByUser(userid); } } else { Response.Redirect("Login"); } }
/// <summary> /// 获取指定状态的客户信息修改审批记录。 /// </summary> /// <param name="approvalStatus"></param> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <param name="orderField"></param> /// <param name="orderDirection"></param> /// <param name="total"></param> /// <returns></returns> public List <CustomerInfoApprovalModel> GetApprovalList(Dictionary <string, QueryItemDomainModel> queryCollection, string approvalStatus, int pageIndex, int pageSize, string orderField, string orderDirection, out int total) { List <CustomerInfoApprovalModel> list = null; StringBuilder sqlBuilder = new StringBuilder(); ParameterCollection pc = new ParameterCollection(); total = 0; sqlBuilder.Append(@" FROM customer_info_approval WHERE 1 = 1 "); if (!string.IsNullOrEmpty(approvalStatus)) { sqlBuilder.Append(@" AND status = $status$ "); pc.Add("status", approvalStatus); } #region 构造查询条件 int count = 0; foreach (QueryItemDomainModel item in queryCollection.Values) { switch (item.Operation) { case "equal": sqlBuilder.AppendFormat(@" AND {0} = $value{1}$", item.FieldType, count); pc.Add("value" + count.ToString(), item.SearchValue); break; case "notequal": sqlBuilder.AppendFormat(@" AND {0} <> $value{1}$", item.FieldType, count); pc.Add("value" + count.ToString(), item.SearchValue); break; case "contain": sqlBuilder.AppendFormat(@" AND {0} LIKE $value{1}$", item.FieldType, count); pc.Add("value" + count.ToString(), "%" + item.SearchValue + "%"); break; case "greater": sqlBuilder.AppendFormat(@" AND {0} > $value{1}$", item.FieldType, count); pc.Add("value" + count.ToString(), item.SearchValue); break; case "greaterequal": sqlBuilder.AppendFormat(@" AND {0} >= $value{1}$", item.FieldType, count); pc.Add("value" + count.ToString(), item.SearchValue); break; case "less": sqlBuilder.AppendFormat(@" AND {0} < $value{1}$", item.FieldType, count); pc.Add("value" + count.ToString(), item.SearchValue); break; case "lessequal": sqlBuilder.AppendFormat(@" AND {0} <= $value{1}$", item.FieldType, count); pc.Add("value" + count.ToString(), item.SearchValue); break; case "between": sqlBuilder.AppendFormat(@" AND {0} BETWEEN $begin{1}$ AND $end{1}$", item.FieldType, count); pc.Add("begin" + count.ToString(), item.BeginTime); pc.Add("end" + count.ToString(), item.EndTime); break; case "today": sqlBuilder.AppendFormat(@" AND DATEDIFF(DAY,{0},GETDATE()) = 0", item.FieldType); break; case "week": sqlBuilder.AppendFormat(@" AND DATEDIFF(WEEK,{0},GETDATE()) = 0", item.FieldType); break; case "month": sqlBuilder.AppendFormat(@" AND DATEDIFF(MONTH,{0},GETDATE()) = 0", item.FieldType); break; case "quarter": sqlBuilder.AppendFormat(@" AND DATEDIFF(QUARTER,{0},GETDATE()) = 0", item.FieldType); break; case "year": sqlBuilder.AppendFormat(@" AND DATEDIFF(YEAR,{0},GETDATE()) = 0", item.FieldType); break; default: break; } count++; } #endregion total = Convert.ToInt32(ExecuteScalar("SELECT COUNT(1) " + sqlBuilder.ToString(), pc)); DataTable dt = ExecuteDataTable("SELECT * " + sqlBuilder.ToString(), pc, pageIndex, pageSize, OrderByCollection.Create("customer_info_approval." + orderField, orderDirection)); list = ModelConvertFrom <CustomerInfoApprovalModel>(dt); return(list); }
/// <summary> /// 更新指定客户信息修改审批记录。 /// </summary> /// <param name="idList"></param> /// <param name="status"></param> /// <param name="message"></param> /// <returns></returns> public bool UpdateCustomerApprovalStatus(List <string> idList, string approvalDescription, int status, out string message) { bool result = false; message = "操作失败,请与管理员联系"; if (idList == null || idList.Count == 0) { return(false); } try { BeginTransaction(); string sql = "update customer_info_approval set status = $status$, description = $description$ where approval_id = $id$"; string updateCustomerSQL = "update customer_basic_info set level = $level$ where customer_id = $customer_id$"; ParameterCollection pc = new ParameterCollection(); pc.Add("status", status); pc.Add("id", ""); pc.Add("customer_id", ""); pc.Add("level", ""); pc.Add("description", (approvalDescription == null) ? "" : approvalDescription); for (int i = 0; i < idList.Count; i++) { pc["id"].Value = idList[i]; CustomerInfoApprovalModel approvalInfo = Retrieve(idList[i]); if (approvalInfo == null) { message = "操作失败,不存在的客户信息修改审批ID"; return(false); } if (ExecuteNonQuery(sql, pc) != 1) { RollbackTransaction(); message = "更新审批记录失败,请与管理员联系"; LogUtil.Debug(string.Format("更新ID为【{0}】的客户信息修改审批记录状态失败", approvalInfo.ApprovalId)); return(false); } else { pc["customer_id"].Value = approvalInfo.CustomerId; if (status == 2) { pc["level"].Value = approvalInfo.NewDataId; } else if (status == 1) { pc["level"].Value = approvalInfo.OldData; } if (ExecuteNonQuery(updateCustomerSQL, pc) != 1) { RollbackTransaction(); message = "更新客户等级信息失败,请与管理员联系"; LogUtil.Debug(string.Format("更新ID为【{0}】的客户信息修改审核记录状态失败,客户ID为【{1}】", approvalInfo.ApprovalId, approvalInfo.CustomerId)); return(false); } else { CustomerMemoInfoModel memoInfo = new CustomerMemoInfoModel(); memoInfo.CustomerId = approvalInfo.CustomerId; if (status == 1) { memoInfo.Memo = string.Format("客户信息修改审核未通过,“{0}”原值【{1}】改为【{2}】, {3}", approvalInfo.UpdateFieldName, approvalInfo.NewData, approvalInfo.OldData, approvalDescription); } else if (status == 2) { memoInfo.Memo = string.Format("客户信息修改审核通过,“{0}”原值【{1}】改为【{2}】, {3}", approvalInfo.UpdateFieldName, approvalInfo.OldData, approvalInfo.NewData, approvalDescription); } memoInfo.MemoId = GetGuid(); memoInfo.Status = 0; if (CustomerMemoInfoService.Instance.CreateMemoInfo(memoInfo, out message) == false) { RollbackTransaction(); return(false); } CustomerInfoService.Instance.GetCustomerDomainModelById(approvalInfo.CustomerId, true); } } } CommitTransaction(); message = "成功提交客户审核信息"; result = true; } catch (Exception ex) { RollbackTransaction(); LogUtil.Error("通过客户信息修改审批异常", ex); throw ex; } return(result); }