protected void btnComment_Click(object sender, ImageClickEventArgs e) { DataSet ds; DataHelper _DataHelper = new DataHelper(); int bbsid = 0; if (this.TextBox1.Text.Trim() != "") { ds = _DataHelper.ReadDb("select top 1 postid from HairShop where HairShopID=" + HairShopID); if (ds.Tables[0].Rows.Count > 0) { bbsid = int.Parse(ds.Tables[0].Rows[0][0].ToString()); if (UserID == "") { _DataHelper.NoNameComment(bbsid, 72, this.TextBox1.Text.Trim()); } else { _DataHelper.HaveNameComment(bbsid, 72, UserName, UserID, this.TextBox1.Text.Trim()); } this.UserComment.Text = ReadComment(bbsid.ToString()).ToString(); } } this.Response.Redirect(this.Request.Url.ToString()); }
public MainPageViewModel(BabyFeedSettings babyFeedSettings, DataHelper dataHelper, INavigationService navService) { settings = babyFeedSettings; this.dataHelper = dataHelper; this.navService = navService; Feeds = dataHelper.GetTodaysFeeds(); FeedTime = DateTime.Now; SetReminder = settings.Reminder; }
public ProvinceDL() { try { dbh = new DataHelper(); } catch (Exception ex) { } }
public BookingDL() { try { dbh = new DataHelper(); } catch (Exception ex) { } }
public GrapherDL() { try { dbh = new DataHelper(); } catch (Exception ex) { } }
public virtual IServiceContainer CreateServiceContainer(Type dataServiceType, IPrincipal principal) { var serviceContainer = new ServiceContainer(); var authorizer = new AuthorizerClass(dataServiceType, principal); serviceContainer.AddService(typeof(IAuthorizer), authorizer); var valueConverter = new ValueConverter(serviceContainer); serviceContainer.AddService(typeof(IValueConverter), valueConverter); var dataHelper = new DataHelper(serviceContainer); serviceContainer.AddService(typeof(IDataHelper), dataHelper); var validationHelper = new ValidationHelper(serviceContainer); serviceContainer.AddService(typeof(IValidationHelper), validationHelper); var queryHelper = new QueryHelper(serviceContainer); serviceContainer.AddService(typeof(IQueryHelper), queryHelper); return serviceContainer; }
public SeedBase(string SeedVersion, ContentModel db, UmbracoProvider provider) { helper = new DataHelper(); mapper = new EntityMapper(helper); UProvider = provider; //IMPORTANT: REMOVE Guid.NewGuid() from seed version ID and change it to Guid.Parse(SeedVersion); SeedVersionID = Guid.Parse(SeedVersion); Db = db; if (Db.SeedVersions.Find(SeedVersionID) == null) { SeedCanRun = true; } else { SeedCanRun = false; } }
public BaseAPIController() { // HandleOptions(); IDataHelper helper = new DataHelper(); IEntityMapper mapper = new EntityMapper(helper); string headerDateTime = ""; string culture = ""; string country = ""; string[] languages = HttpContext.Current.Request.UserLanguages; if (languages == null || languages.Length == 0) { culture = CultureInfo.InvariantCulture.Name; } else { string language = languages[0].ToLowerInvariant().Trim(); culture = CultureInfo.CreateSpecificCulture(language).Name; } if (HttpContext.Current.Request.Headers["UserDateTime"] != null) { headerDateTime = HttpContext.Current.Request.Headers["UserDateTime"]; } else if (HttpContext.Current.Request["UserDateTime"] != null) { headerDateTime = HttpContext.Current.Request["UserDateTime"]; } else { headerDateTime = DateTime.Now.Ticks.ToString(); } UserDateTime = new DateTime(long.Parse(headerDateTime)); UserCulture = new CultureInfo(culture); Thread.CurrentThread.CurrentCulture.ClearCachedData(); Thread.CurrentThread.CurrentCulture = UserCulture; Thread.CurrentThread.CurrentUICulture = UserCulture; _RegionInfo = RegionInfo.CurrentRegion; }
protected void Run(object state) { try { if (!REQUESTING) { REQUESTING = true; new Task((Action)(async () => { DataHelper helper = new DataHelper(); string request = helper.GenerateRequest(); if (request.Contains("<resource>")) { string response = await WebRequests.ReqResp(request); string answare = helper.SQLUpdates(response); if (answare.Contains("<resource>")) { string confirmResp = await WebRequests.ReqResp(answare); helper.InsertLog(request, response, answare); } else { helper.InsertLog(request, response, ""); } } REQUESTING = false; })).Start(); } } catch (Exception eex) { DataHelper helper = new DataHelper(); helper.InsertLog(eex.Message, eex.StackTrace, ""); //EventsLog.WriteEntry("EXCEPTION: " + eex.Message); } }
public DBAccess() { data = new DataHelper(); LoadModels(); }
/// <summary> /// Loads the data. /// </summary> protected void LoadData() { lblValueAlocatedMemory.Text = DataHelper.GetSizeString(GC.GetTotalMemory(false)); lblValueVirtualMemory.Text = "N/A"; lblValuePhysicalMemory.Text = "N/A"; lblValuePeakMemory.Text = "N/A"; // Process memory try { lblValueVirtualMemory.Text = DataHelper.GetSizeString(SystemHelper.GetVirtualMemorySize()); lblValuePhysicalMemory.Text = DataHelper.GetSizeString(SystemHelper.GetWorkingSetSize()); lblValuePeakMemory.Text = DataHelper.GetSizeString(SystemHelper.GetPeakWorkingSetSize()); } catch { } this.lblValuePages.Text = GetViewValues(RequestHelper.TotalPageRequests.GetValue(null), 0, mRPSPageRequests); this.lblValuePagesNotFound.Text = GetViewValues(RequestHelper.TotalPageNotFoundRequests.GetValue(null), 0, mRPSPageNotFoundRequests); this.lblValueSystemPages.Text = GetViewValues(RequestHelper.TotalSystemPageRequests.GetValue(null), 0, mRPSSystemPageRequests); this.lblValueNonPages.Text = GetViewValues(RequestHelper.TotalNonPageRequests.GetValue(null), 0, mRPSNonPageRequests); this.lblValueGetFilePages.Text = GetViewValues(RequestHelper.TotalGetFileRequests.GetValue(null), 0, mRPSGetFileRequests); long pending = RequestHelper.PendingRequests.GetValue(null); if (pending > 1) { // Current request does not count as pending at the time of display pending--; } if (pending < 0) { pending = 0; } this.lblValuePending.Text = pending.ToString(); this.lblCacheItemsValue.Text = Cache.Count.ToString(); this.lblCacheExpiredValue.Text = CacheHelper.Expired.GetValue(null).ToString(); this.lblCacheRemovedValue.Text = CacheHelper.Removed.GetValue(null).ToString(); this.lblCacheUnderusedValue.Text = CacheHelper.Underused.GetValue(null).ToString(); this.lblCacheDependencyValue.Text = CacheHelper.DependencyChanged.GetValue(null).ToString(); // GC collections try { this.plcGC.Controls.Clear(); int generations = GC.MaxGeneration; for (int i = 0; i <= generations; i++) { int count = GC.CollectionCount(i); string genString = "<tr><td style=\"white-space: nowrap; width: 200px;\">" + GetString("GC.Generation") + " " + i.ToString() + ":</td><td>" + count.ToString() + "</td></tr>"; this.plcGC.Controls.Add(new LiteralControl(genString)); } } catch { } lblDBNameValue.Text = TableManager.DatabaseName; lblServerVersionValue.Text = TableManager.DatabaseServerVersion; // DB information if (!RequestHelper.IsPostBack()) { lblDBSizeValue.Text = TableManager.DatabaseSize; lblServerNameValue.Text = TableManager.DatabaseServerName; } }
private bool CheckUpdateTradeMemoParameters(SortedDictionary <string, string> parameters, out int flag, ref string result) { flag = 0; if (!OpenApiHelper.CheckSystemParameters(parameters, this.site.AppKey, out result)) { return(false); } if (string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["tid"]))) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Missing_Required_Arguments, "tid"); return(false); } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["flag"]))) { if (!int.TryParse(DataHelper.CleanSearchString(parameters["flag"]), out flag)) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Parameters_Format_Error, "flag"); return(false); } if ((flag < 1) || (flag > 6)) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Trade_Flag_Too_Long, "flag"); return(false); } } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["memo"])) && (DataHelper.CleanSearchString(parameters["memo"]).Length > 300)) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Trade_Memo_Too_Long, "memo"); return(false); } Regex regex = new Regex("^(?!_)(?!.*?_$)(?!-)(?!.*?-$)[a-zA-Z0-9._一-龥-]+$"); if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["memo"])) && !regex.IsMatch(DataHelper.CleanSearchString(parameters["memo"]))) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Parameters_Format_Error, "memo"); return(false); } return(true); }
private System.Text.StringBuilder ReadComment(string BBSID) { System.Text.StringBuilder Txt = new System.Text.StringBuilder(); Txt.Append(""); DataSet ds = new DataSet(); DataHelper _DataHelper = new DataHelper(); if (_DataHelper.ReadBssComment(BBSID, "10", out ds)) { if (ds.Tables[0].Rows.Count > 0) { int i = 0; foreach (DataRow thisRow in ds.Tables[0].Rows) { i++; string author = ""; if (thisRow["author"].ToString() != string.Empty) { author = "<a href='http://u.sg.com.cn/space-" + thisRow["authorid"].ToString() + ".html' target='_blank'>" + thisRow["author"].ToString() + "</a>"; } else { author ="��Ʒ��˿"; } Txt.AppendFormat(" <div class=\"message-{0}\">", i % 2 == 1 ? 2 : 1); Txt.AppendFormat(" "); Txt.AppendFormat(" <div class=\"touxiang\"><div class=\"touxiang-2\"><a href='http://u.sg.com.cn/space-" + thisRow["authorid"].ToString() + ".html' target='_blank'><img src=\"http://bbs.sg.com.cn/ucenter/avatar.php?uid={0}&size=small\" /></a></div></div>", thisRow["authorid"].ToString()); Txt.AppendFormat(" <div class=\"mes-content\"><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"); Txt.AppendFormat(" <tr>"); Txt.AppendFormat(" <td width=\"18%\" align=\"left\" valign=\"top\" class=\"black12\">{0}��</td>", author); Txt.AppendFormat("<td width=\"60%\" align=\"left\" class=\"black12\">{0}</td>", thisRow["message"].ToString()); Txt.AppendFormat("<td width=\"22%\" align=\"right\" valign=\"top\" class=\"gray12\">{0}<br /></td>", HWCommon.Util.BBsDate(int.Parse(thisRow["lastpost"].ToString()))); Txt.AppendFormat(" </td>"); Txt.AppendFormat(" </tr>"); Txt.AppendFormat("</table>"); Txt.AppendFormat("<div class=\"point\"></div>"); Txt.AppendFormat(" "); Txt.AppendFormat(" </div>"); Txt.AppendFormat(" <div class=\"clear\"></div>"); Txt.AppendFormat(" </div>"); } } } return Txt; }
/// <summary> /// Renders the particular cache item. /// </summary> protected void RenderItem(StringBuilder sb, string key, CacheItemContainer container, object value, bool dummy, int i) { // Add the key row string cssClass = ((i % 2) == 0) ? "OddRow" : "EvenRow"; sb.Append("<tr class=\""); sb.Append(cssClass); sb.Append("\"><td style=\"white-space: nowrap;\">"); // Get the action GetDeleteAction(key, sb); sb.Append("</td><td style=\"white-space: nowrap;\"><span title=\"" + key.Replace("&", "&") + "\">"); string keyTag = TextHelper.LimitLength(key, 100); sb.Append(keyTag.Replace("&", "&")); sb.Append("</span></td>"); if (!dummy) { sb.Append("<td style=\"white-space: nowrap;\">"); // Render the value if (value != null) { sb.Append("<a href=\"#\" onclick=\"Show('" + Server.UrlEncode(key) + "')\""); sb.Append("><img class=\"UniGridActionButton\" src=\""); sb.Append(ResolveUrl(GetImageUrl("Design/Controls/UniGrid/Actions/View.png"))); sb.Append("\" style=\"border: none;\" alt=\""); sb.Append(GetString("General.View")); sb.Append("\" title=\""); sb.Append(GetString("General.View")); sb.Append("\" />"); sb.Append("</a> "); if ((value == null) || (value == DBNull.Value)) { sb.Append("null"); } else { sb.Append(HttpUtility.HtmlEncode(DataHelper.GetObjectString(value, 100))); } } else { sb.Append("null"); } sb.Append("</td>"); if (CacheHelper.DebugCache) { // Expiration sb.Append("<td style=\"white-space: nowrap;\">"); if (container != null) { if (container.AbsoluteExpiration != System.Web.Caching.Cache.NoAbsoluteExpiration) { sb.Append(container.AbsoluteExpiration); } else { sb.Append(container.SlidingExpiration); } } sb.Append("</td>"); // Expiration sb.Append("<td style=\"white-space: nowrap;\">"); if (container != null) { sb.Append(container.Priority); } sb.Append("</td>"); } } sb.Append("</tr>"); }
protected void Page_Init(object sender, EventArgs e) { var user = MembershipContext.AuthenticatedUser; // Check the license and site availability for Newsletters switch (ObjectType) { case PredefinedObjectType.NEWSLETTERISSUE: case PredefinedObjectType.NEWSLETTERISSUEVARIANT: case PredefinedObjectType.NEWSLETTERTEMPLATE: { // Check the license if (!string.IsNullOrEmpty(DataHelper.GetNotEmpty(RequestContext.CurrentDomain, string.Empty))) { LicenseHelper.CheckFeatureAndRedirect(RequestContext.CurrentDomain, FeatureEnum.Newsletters); } // Check site availability if (!ResourceSiteInfoProvider.IsResourceOnSite("CMS.Newsletter", SiteContext.CurrentSiteName)) { RedirectToResourceNotAvailableOnSite("CMS.Newsletter"); } // Check UI permissions for CMS Desk -> Tools -> Newsletter if (!user.IsAuthorizedPerUIElement("CMS.Newsletter", "Newsletter")) { RedirectToUIElementAccessDenied("CMS.Newsletter", "Newsletter"); } } break; } // Check permissions switch (ObjectType) { case PredefinedObjectType.NEWSLETTERISSUE: case PredefinedObjectType.NEWSLETTERISSUEVARIANT: // Check 'AuthorIssues' permission if (!user.IsAuthorizedPerResource("CMS.Newsletter", "AuthorIssues")) { RedirectToAccessDenied("CMS.Newsletter", "AuthorIssues"); } break; case PredefinedObjectType.NEWSLETTERTEMPLATE: // Check 'Managetemplates' permission if (!user.IsAuthorizedPerResource("CMS.Newsletter", "managetemplates")) { RedirectToAccessDenied("CMS.Newsletter", "managetemplates"); } break; case PredefinedObjectType.BIZFORM: // Check 'EditForm' permission if (!user.IsAuthorizedPerResource("cms.form", "EditForm")) { RedirectToAccessDenied("cms.form", "EditForm"); } break; case EmailTemplateInfo.OBJECT_TYPE: // Check "Modify" permission if (!user.IsAuthorizedPerResource("CMS.EmailTemplates", "Modify")) { RedirectToAccessDenied("CMS.EmailTemplates", "Modify"); } break; } }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { gridElem.StopProcessing = true; } else { gridElem.ControlContext = ControlContext; gridElem.EnableViewState = true; // Set properties from web part form gridElem.CacheItemName = CacheItemName; gridElem.CacheDependencies = CacheDependencies; gridElem.CacheMinutes = CacheMinutes; gridElem.CheckPermissions = CheckPermissions; gridElem.ClassNames = ClassNames; gridElem.CategoryName = CategoryName; gridElem.CombineWithDefaultCulture = CombineWithDefaultCulture; gridElem.FilterOutDuplicates = FilterOutDuplicates; gridElem.CultureCode = CultureCode; gridElem.MaxRelativeLevel = MaxRelativeLevel; gridElem.OrderBy = OrderBy; gridElem.RelatedNodeIsOnTheLeftSide = RelatedNodeIsOnTheLeftSide; gridElem.RelationshipName = RelationshipName; gridElem.RelationshipWithNodeGuid = RelationshipWithNodeGUID; gridElem.SelectedItemTransformationName = SelectedItemTransformationName; gridElem.Path = Path; gridElem.SelectTopN = SelectTopN; gridElem.SelectedColumns = SelectedColumns; gridElem.SelectOnlyPublished = SelectOnlyPublished; gridElem.SiteName = SiteName; gridElem.WhereCondition = WhereCondition; gridElem.HideControlForZeroRows = HideControlForZeroRows; gridElem.ZeroRowsText = ZeroRowsText; if (!StandAlone && (PageCycle < PageCycleEnum.Initialized) && (ValidationHelper.GetString(Page.StyleSheetTheme, "") == "")) { gridElem.SkinID = SkinID; } gridElem.SortAscending = SortAscending; gridElem.AllowSorting = AllowSorting; gridElem.ProcessSorting = ProcessSorting; gridElem.SortField = SortField; gridElem.AllowPaging = AllowPaging; gridElem.AllowCustomPaging = AllowCustomPaging; gridElem.PageSize = PageSize; gridElem.DataBindByDefault = DataBindByDefault; gridElem.SelectTopN = SelectTopN; gridElem.PagerStyle.Mode = PagingMode; gridElem.FilterName = FilterName; gridElem.ShowHeader = ShowHeader; gridElem.ShowFooter = ShowFooter; gridElem.ToolTip = ToolTip; gridElem.SetFirstPageAfterSortChange = SetFirstPageAfterSortChange; // CMSEditModeButtonAdd btnAdd.Visible = ShowNewButton; btnAdd.Text = NewButtonText; string[] mClassNames = gridElem.ClassNames.Split(';'); btnAdd.ClassName = DataHelper.GetNotEmpty(mClassNames[0], ""); string mPath = ""; if (gridElem.Path.EndsWithCSafe("/%")) { mPath = gridElem.Path.Remove(gridElem.Path.Length - 2); } if (gridElem.Path.EndsWithCSafe("/")) { mPath = gridElem.Path.Remove(gridElem.Path.Length - 1); } btnAdd.Path = DataHelper.GetNotEmpty(mPath, ""); LoadFromDataClass(gridElem.ClassNames); InitColumns(ColumnsSelector); /*if (RequestHelper.IsPostBack()) * { * this.gridElem.ReloadData(true); * }*/ gridElem.DataBindByDefault = false; } }
static HelperFactory() { DataHelper = new DataHelper(); }
private void ShowInThisPage(int type) { System.Text.StringBuilder txt = new System.Text.StringBuilder(); DataHelper _DataHelper = new DataHelper(); string Sql = ""; string SqlTop = ""; Sql = string.Format("select * from dbo.History where ProductID={0} and type={1} order by HistoryId desc", HairShopID, type); SqlTop = string.Format("select top 3 * from dbo.History where ProductID={0} and type={1} order by HistoryId desc", HairShopID, type); if (UserID != "") { //�Ѿ���½����δ��֤ // Sql += string.Format(" and UserID<>{0}", UserID); // SqlTop += string.Format(" and UserID<>{0}", UserID); } else { this.CaiBottom.Visible = false; } DataSet ds = _DataHelper.ReadDb(Sql); DataSet dsTop = _DataHelper.ReadDb(SqlTop); txt.AppendFormat("<table width=\"90%\" border=\"0\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\" style=\"margin-top:15px\">"); txt.AppendFormat("<tr>"); lblCaiCount.Text = ds.Tables[0].Rows.Count.ToString(); if (ds.Tables[0].Rows.Count > 0) { foreach (DataRow thisPicRow in dsTop.Tables[0].Rows) { txt.AppendFormat("<td width=\"50%\" align=\"center\" valign=\"top\"><div class=\"pic-5\"><a href=\"http://u.sg.com.cn/space-{0}.html\" target=\"_blank\"><img src=\"http://bbs.sg.com.cn/ucenter/avatar.php?uid={0}&size=small\" /></a></div><div class=\"pic-5-title\"><a href=\"http://u.sg.com.cn/space-{0}.html\" target=\"_blank\"><span class=\"gray\">{1}</span></a></div>", thisPicRow["UserID"].ToString(), thisPicRow["UserName"].ToString()); txt.AppendFormat("</td>"); //txt.AppendFormat("<span class=\"gray12-c\"><a href=\"http://u.sg.com.cn/space-{0}.html\" target=\"_blank\">{1}</a></span></td>", thisPicRow["UserID"].ToString(), thisPicRow["UserName"].ToString()); } } txt.AppendFormat("</tr>"); txt.AppendFormat("</table>"); this.UserBrow.Text = txt.ToString(); //�Ƿ���ʵ�Ȱ�ť if (UserID != "") { Sql = string.Format("select * from History where ProductID={0} and UserID={1} and type={2}", HairShopID, UserID, type); ds = new DataSet(); ds = _DataHelper.ReadDb(Sql); if (ds.Tables[0].Rows.Count > 0) { this.CaiBottom.Visible = false; } else { this.CaiBottom.Visible = true; } } }
public Login() { InitializeComponent(); dh = new DataHandler(); proxy = new LoginClient(); }
public void LoadBySubqueryAndRelation() { StorageContext.CreateTestDataSchema(); var schema = StorageContext.DataSchemaStorage.GetSchema(); var contactsClass = schema.FindClassByID("contacts"); var companiesClass = schema.FindClassByID("companies"); var emplClass = schema.FindClassByID("employee"); Assert.NotNull(emplClass); var contactCompanyEmployeeRel = contactsClass.FindRelationship( emplClass, companiesClass ); Assert.NotNull(contactCompanyEmployeeRel); using (var t = new TransactionScope()) { DataHelper.EnsureConnectionOpen(StorageContext.Connection, () => { for (int i=0; i<10; i++) { var objCompany = new ObjectContainer(companiesClass); objCompany["name"] = String.Format("Company_{0}", i); StorageContext.ObjectContainerStorage.Insert(objCompany); for (int j=0; j<10; j++) { var objContact = new ObjectContainer(contactsClass); objContact["name"] = String.Format("Company_{0} Contact_{1}", i, j); StorageContext.ObjectContainerStorage.Insert(objContact); StorageContext.ObjectContainerStorage.AddRelation( new ObjectRelation(objContact.ID.Value, contactCompanyEmployeeRel, objCompany.ID.Value ) ); } } }); t.Complete(); } // subquery test Assert.AreEqual("Company_1", StorageContext.StorageDalc.LoadValue( new Query("companies", new QueryConditionNode( (QField)"id", Conditions.In, new Query("contacts_employee_companies", new QueryConditionNode( (QField)"subject_id", Conditions.In, new Query("contacts", new QueryConditionNode((QField)"name", Conditions.Like, (QConst)"Company_1%") ) { Fields = new [] { (QField)"id" } } ) ) { Fields = new[] {(QField)"object_id"} } ) ) { Fields = new [] { (QField)"name" } } ) ); // relation load test var company0rels = StorageContext.ObjectContainerStorage.LoadRelations( "contacts_employee_companies", new QueryConditionNode( (QField)"object_id", Conditions.In, new Query("companies.c", (QField)"name"==(QConst)"Company_0" ) { Fields = new[] { (QField)"c.id" } } ) ); Assert.AreEqual(10, company0rels.Count() ); }
protected void RemoveOld(object state) { try { DataHelper helper = new DataHelper(); helper.DeleteSynchroByDate(DateTime.Now.AddDays(-1)); helper.DeleteLogs(); } catch (Exception eex) { DataHelper helper = new DataHelper(); helper.InsertLog(eex.Message, eex.StackTrace, ""); //EventsLog.WriteEntry("EXCEPTION: " + eex.Message); } }
protected void Page_Load(object sender, EventArgs e) { op = RequestData.Get <string>("op"); id = RequestData.Get <string>("id"); switch (RequestActionString) { case "IsIsbn": string val = RequestData.Get <string>("Value"); IList <Product> proEnts = Product.FindAll("from Product where Isbn='" + val + "'"); if (proEnts.Count > 0) { PageState.Add("IsIsbn", true); } else { PageState.Add("IsIsbn", false); } break; case "GetPackageInfo": string Isbn = RequestData.Get <string>("Isbn"); sql = "select * from SHHG_AimExamine..Products where FirstSkinIsbn='" + Isbn + "' and FirstSkinCapacity is not null"; IList <EasyDictionary> dics = DataHelper.QueryDictList(sql); if (dics.Count > 0) { PageState.Add("ProductIsbn", dics[0].Get <string>("Isbn").ToUpper()); PageState.Add("ProductQuan", dics[0].Get <int>("FirstSkinCapacity")); } sql = "select * from SHHG_AimExamine..Products where SecondSkinIsbn='" + Isbn + "' and SecondSkinCapacity is not null"; dics = DataHelper.QueryDictList(sql); if (dics.Count > 0) { PageState.Add("ProductIsbn", dics[0].Get <string>("Isbn").ToUpper()); PageState.Add("ProductQuan", dics[0].Get <int>("SecondSkinCapacity")); } break; case "ScanSkin": //判断包装编号是否存在 string skinNo = RequestData.Get <string>("SkinNo"); IList <Skin> sEnts = Skin.FindAll("from Skin where SkinNo='" + skinNo + "'"); if (sEnts.Count > 0) //如果该包装的记录不存在 { PageState.Add("SkinExist", true); } else { PageState.Add("SkinExist", false); } break; case "ScanCompressor": string seriesNo = RequestData.Get <string>("SeriesNo"); IList <Compressor> cEnts = Compressor.FindAll("from Compressor where SeriesNo='" + seriesNo + "'"); if (cEnts.Count == 0) { PageState.Add("CompressorExist", false); } else { PageState.Add("CompressorExist", true); } break; case "InWarehouse": InWarehouse iwEnt = InWarehouse.TryFind(id); IList <string> entStrList = RequestData.GetList <string>("data"); if (entStrList != null && entStrList.Count > 0) { for (int j = 0; j < entStrList.Count; j++) { Newtonsoft.Json.Linq.JObject objL = JsonHelper.GetObject <Newtonsoft.Json.Linq.JObject>(entStrList[j]); if (Convert.ToInt32(objL.Value <string>("ActuallyQuantity")) > 0) //只有输入了入库数量才会增加实际入库记录 { InWarehouseDetailDetail iwddEnt = new InWarehouseDetailDetail(); //新建一个实际入库详细信息 if (iwEnt.InWarehouseType == "采购入库") { iwddEnt.InWarehouseDetailId = objL.Value <string>("Id"); iwddEnt.PurchaseOrderDetailId = objL.Value <string>("PurchaseOrderDetailId"); } else //其他入库的情形 { iwddEnt.OtherInWarehouseDetailId = objL.Value <string>("Id"); } iwddEnt.Quantity = Convert.ToInt32(objL.Value <string>("ActuallyQuantity")); iwddEnt.ProductId = objL.Value <string>("ProductId"); iwddEnt.Remark = objL.Value <string>("Remark"); iwddEnt.DoCreate(); StockLog slEnt = new StockLog(); //创建库存变更日志 slEnt.InOrOutDetailId = objL.Value <string>("Id"); slEnt.InOrOutBillNo = iwEnt.InWarehouseNo; slEnt.OperateType = "产品入库"; slEnt.WarehouseId = iwEnt.WarehouseId; slEnt.WarehouseName = iwEnt.WarehouseName; IList <StockInfo> siEnts = StockInfo.FindAllByProperties(StockInfo.Prop_ProductId, objL.Value <string>("ProductId"), StockInfo.Prop_WarehouseId, iwEnt.WarehouseId); if (siEnts.Count > 0) { slEnt.StockQuantity = siEnts[0].StockQuantity; } slEnt.Quantity = Convert.ToInt32(objL.Value <string>("ActuallyQuantity")); slEnt.ProductId = objL.Value <string>("ProductId"); Product pEnt = Product.Find(objL.Value <string>("ProductId")); slEnt.ProductName = pEnt.Name; slEnt.ProductCode = pEnt.Code; slEnt.ProductIsbn = pEnt.Isbn; slEnt.ProductPcn = pEnt.Pcn; slEnt.DoCreate(); ProcessSkin(objL.Value <string>("SkinArray"), objL.Value <string>("ISBN"), iwEnt.Id); ProcessCompressor(objL.Value <string>("SeriesArray"), objL.Value <string>("ISBN"), iwEnt.Id); processremark(objL.Value <string>("Remark"), pEnt, iwEnt.Id); //如果实际入库数量和未入库的数量相等 则入库状态为已入库 if (objL.Value <string>("ActuallyQuantity") == objL.Value <string>("NoIn")) { if (iwEnt.InWarehouseType == "采购入库") { InWarehouseDetail iwdEnt = InWarehouseDetail.Find(objL.Value <string>("Id")); if (!string.IsNullOrEmpty(objL.Value <string>("SkinArray"))) { iwdEnt.SkinArray = objL.Value <string>("SkinArray").ToString(); } if (!string.IsNullOrEmpty(objL.Value <string>("SeriesArray"))) { iwdEnt.SeriesArray = objL.Value <string>("SeriesArray").ToString(); } iwdEnt.InWarehouseState = "已入库"; iwdEnt.DoUpdate(); } else { OtherInWarehouseDetail oiwdEnt = OtherInWarehouseDetail.Find(objL.Value <string>("Id")); oiwdEnt.InWarehouseState = "已入库"; if (!string.IsNullOrEmpty(objL.Value <string>("SkinArray"))) { oiwdEnt.SkinArray = objL.Value <string>("SkinArray").ToString(); } if (!string.IsNullOrEmpty(objL.Value <string>("SeriesArray"))) { oiwdEnt.SeriesArray = objL.Value <string>("SeriesArray").ToString(); } oiwdEnt.DoUpdate(); } } else //如果未入库的数量不等于现在输入的数量。只更新包装和压缩机序列号集合 { if (iwEnt.InWarehouseType == "采购入库") { InWarehouseDetail iwdEnt = InWarehouseDetail.Find(objL.Value <string>("Id")); iwdEnt.Remark = objL.Value <string>("Remark"); if (!string.IsNullOrEmpty(objL.Value <string>("SkinArray"))) { iwdEnt.SkinArray = objL.Value <string>("SkinArray").ToString(); } if (!string.IsNullOrEmpty(objL.Value <string>("SeriesArray"))) { iwdEnt.SeriesArray = objL.Value <string>("SeriesArray").ToString(); } iwdEnt.DoUpdate(); } else { OtherInWarehouseDetail oiwdEnt = OtherInWarehouseDetail.Find(objL.Value <string>("Id")); oiwdEnt.Remark = objL.Value <string>("Remark"); if (!string.IsNullOrEmpty(objL.Value <string>("SkinArray"))) { oiwdEnt.SkinArray = objL.Value <string>("SkinArray").ToString(); } if (!string.IsNullOrEmpty(objL.Value <string>("SeriesArray"))) { oiwdEnt.SeriesArray = objL.Value <string>("SeriesArray").ToString(); } oiwdEnt.DoUpdate(); } } //修改库存 InStorage(iwddEnt.ProductId, iwddEnt.Quantity.Value, iwEnt.WarehouseId); } } } ProcessInWarehouse(iwEnt); if (iwEnt.InWarehouseType == "采购入库") //处理采购单和采购单详细 { ProcessPurchaseOrderAndDetail(iwEnt); } break; default: DoSelect(); break; } }
protected int CheckSn(DataHelper data, NameValueCollection nvc) { if (!nvc.ContainsKey(Constants.Csn)) throw new ExtendedException("SN is missing", (int)Constants.EError.SNMissing); int deviceCode = -1; if (!Int32.TryParse(nvc[Constants.Csn], out deviceCode)) throw new ExtendedException(String.Format("SN [{0}] is invalid", nvc[Constants.Csn]), (int)Constants.EError.SNInvalid); if (!data.CheckSn(deviceCode)) throw new ExtendedException(String.Format("SN [{0}] is unknown", nvc[Constants.Csn]), (int)Constants.EError.SNUnknown); return deviceCode; }
protected DataSet gridDocuments_OnDataReload(string completeWhere, string currentOrder, int currentTopN, string columns, int currentOffset, int currentPageSize, ref int totalRecords) { if (Node == null) { return(null); } // Get documents string currentSiteName = SiteContext.CurrentSiteName; int topN = gridLanguages.GridView.PageSize * (gridLanguages.GridView.PageIndex + 1 + gridLanguages.GridView.PagerSettings.PageButtonCount); columns = SqlHelper.MergeColumns(SqlHelper.MergeColumns(DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS, columns), "DocumentModifiedWhen, DocumentLastVersionNumber, DocumentLastPublished, DocumentIsWaitingForTranslation"); var query = DocumentHelper.GetDocuments() .OnSite(currentSiteName) .Path(Node.NodeAliasPath) .AllCultures() .Published(false) .TopN(topN) .Columns(columns); // Do not apply published from / to columns to make sure the published information is correctly evaluated query.Properties.ExcludedVersionedColumns = new[] { "DocumentPublishFrom", "DocumentPublishTo" }; var data = query.Result; if (DataHelper.DataSourceIsEmpty(data)) { return(null); } var documents = data.Tables[0]; // Get site cultures var allSiteCultures = CultureSiteInfoProvider.GetSiteCultures(currentSiteName).Copy(); // Rename culture column to enable row transfer allSiteCultures.Tables[0].Columns[2].ColumnName = "DocumentCulture"; // Create where condition for row transfer string where = documents.Rows.Cast <DataRow>().Aggregate("DocumentCulture NOT IN (", (current, row) => current + ("'" + SqlHelper.EscapeQuotes(ValidationHelper.GetString(row["DocumentCulture"], string.Empty)) + "',")); where = where.TrimEnd(',') + ")"; // Transfer missing cultures, keep original list of site cultures DataHelper.TransferTableRows(documents, allSiteCultures.Copy().Tables[0], where, null); DataHelper.EnsureColumn(documents, "DocumentCultureDisplayName", typeof(string)); // Ensure culture names foreach (DataRow cultDR in documents.Rows) { string cultureCode = cultDR["DocumentCulture"].ToString(); DataRow[] cultureRow = allSiteCultures.Tables[0].Select("DocumentCulture='" + cultureCode + "'"); if (cultureRow.Length > 0) { cultDR["DocumentCultureDisplayName"] = cultureRow[0]["CultureName"].ToString(); } } // Ensure default culture to be first DataRow[] cultureDRs = documents.Select("DocumentCulture='" + DefaultSiteCulture + "'"); if (cultureDRs.Length <= 0) { throw new Exception("[ReloadData]: Default site culture '" + DefaultSiteCulture + "' is not assigned to the current site."); } DataRow defaultCultureRow = cultureDRs[0]; DataRow dr = documents.NewRow(); dr.ItemArray = defaultCultureRow.ItemArray; documents.Rows.InsertAt(dr, 0); documents.Rows.Remove(defaultCultureRow); // Get last modification date of default culture defaultCultureRow = documents.Select("DocumentCulture='" + DefaultSiteCulture + "'")[0]; defaultLastModification = ValidationHelper.GetDateTime(defaultCultureRow["DocumentModifiedWhen"], DateTimeHelper.ZERO_TIME); defaultLastPublished = ValidationHelper.GetDateTime(defaultCultureRow["DocumentLastPublished"], DateTimeHelper.ZERO_TIME); // Add column containing translation status documents.Columns.Add("TranslationStatus", typeof(TranslationStatusEnum)); // Get proper translation status and store it to datatable foreach (DataRow document in documents.Rows) { TranslationStatusEnum status; int documentId = ValidationHelper.GetInteger(document["DocumentID"], 0); if (documentId == 0) { status = TranslationStatusEnum.NotAvailable; } else { string versionNumber = DataHelper.GetStringValue(document, "DocumentLastVersionNumber", null); if (ValidationHelper.GetBoolean(document["DocumentIsWaitingForTranslation"], false)) { status = TranslationStatusEnum.WaitingForTranslation; } else { DateTime lastModification; // Check if document is outdated if (versionNumber != null) { lastModification = ValidationHelper.GetDateTime(document["DocumentLastPublished"], DateTimeHelper.ZERO_TIME); status = (lastModification < defaultLastPublished) ? TranslationStatusEnum.Outdated : TranslationStatusEnum.Translated; } else { lastModification = ValidationHelper.GetDateTime(document["DocumentModifiedWhen"], DateTimeHelper.ZERO_TIME); status = (lastModification < defaultLastModification) ? TranslationStatusEnum.Outdated : TranslationStatusEnum.Translated; } } } document["TranslationStatus"] = status; } // Bind datasource DataSet filteredDocuments = data.Clone(); DataRow[] filteredDocs = documents.Select(gridLanguages.GetFilter()); foreach (DataRow row in filteredDocs) { filteredDocuments.Tables[0].ImportRow(row); } return(filteredDocuments); }
public HttpResponseMessage Post(FormDataCollection formData) { NameValueCollection inParams = FormDataConvert(formData); DataHelper data = new DataHelper(); List<KeyValuePair<string, string>> outParams = new List<KeyValuePair<string, string>>(); decimal? a02id = null; Constants.EEvent eevent = Constants.EEvent.NoEvent; try { // UNIQUEID bool? confirmed = null; if (inParams.ContainsKey(Constants.Cuniqueid)) { confirmed = data.ConfirmSynchro(inParams[Constants.Cuniqueid], ref outParams); } // SOURCE int deviceCode = CheckSn(data, inParams); // COMAPNY a02id = data.GetCompanyIdByDeviceCode(deviceCode); data.UpdateHeartBeat(deviceCode); bool init = false; if (inParams.ContainsKey(Constants.Cinit)) { init = inParams[Constants.Cinit] == "1"; } // aktualizace a02id a s10event eevent = CheckEvent(inParams, init, confirmed); if (init) { switch (eevent) { case Constants.EEvent.Device: data.SetDeviceInit(deviceCode, ref outParams); break; case Constants.EEvent.Bottle: data.SetBottleInit(deviceCode, ref outParams); break; case Constants.EEvent.DateTime: data.StringToDictionary(Constants.Cevent, ((short)Constants.EEvent.DateTime).ToString(), ref outParams); data.StringToDictionary(Constants.Cdatetime, DateTime.Now.AddYears(-1600).Ticks.ToString(), ref outParams); break; default: throw new ExtendedException(String.Format("EventId [{0}] unhandled", ((int)eevent).ToString()), (int)Constants.EError.EventUnhandled); } } else { switch (eevent) { // Změnap oslaná ze zařízení (automatické otvírání/zavírání) case Constants.EEvent.Device: data.SetDevice(deviceCode, inParams, ref outParams); break; //Ověření výdeje case Constants.EEvent.VerifyDispense: data.Dispense(deviceCode, inParams, ref outParams, true); break; case Constants.EEvent.InsertDispense: //vydej data.Dispense(deviceCode, inParams, ref outParams); data.CloudSynchro(deviceCode, Constants.EEvent.InsertDispense, formData); break; case Constants.EEvent.BottleChange: //vymena lahve data.ChangeBottle(deviceCode, inParams, ref outParams); data.CloudSynchro(deviceCode, Constants.EEvent.BottleChange, formData); break; case Constants.EEvent.CardVerify: //overeni karty data.VerifyCard(deviceCode, inParams, ref outParams); break; case Constants.EEvent.HeartBeat: // HeartBeat data.GetChanges(null, deviceCode, (short)Constants.EEvent.HeartBeat, ref outParams); break; default: data.GetChanges(null, deviceCode, null, ref outParams); break; } } if (confirmed.HasValue) { data.StringToDictionary(Constants.Cconfirmed, String.Format("{0}:{1}", inParams[Constants.Cuniqueid], confirmed.ToString()), ref outParams); } } catch (ExtendedException eex) { outParams.Clear(); outParams.Add(new KeyValuePair<string, string>(Constants.Cresult, Constants.CResValErr)); outParams.Add(new KeyValuePair<string, string>(Constants.Cexception, eex.Message)); outParams.Add(new KeyValuePair<string, string>(Constants.Cerrcode, eex.ErrCode.ToString())); outParams.Add(new KeyValuePair<string, string>(Constants.Cversion, CVersion)); } catch (Exception ex) { outParams.Clear(); outParams.Add(new KeyValuePair<string, string>(Constants.Cresult, Constants.CResErr)); outParams.Add(new KeyValuePair<string, string>(Constants.Cexception, ex.Message)); outParams.Add(new KeyValuePair<string, string>(Constants.Cversion, CVersion)); } finally { if (outParams.Count == 0) { outParams.Add(new KeyValuePair<string, string>(Constants.Cresult, Constants.CResErr)); outParams.Add(new KeyValuePair<string, string>(Constants.Cexception, "No data received")); outParams.Add(new KeyValuePair<string, string>(Constants.Cerrcode, Constants.EError.NoDataReceived.ToString())); outParams.Add(new KeyValuePair<string, string>(Constants.Cversion, CVersion)); } } string result = GenerateResponseString(outParams); return new HttpResponseMessage() { Content = new StringContent( result, Encoding.UTF8, "text/html" ) }; }
protected void Page_Load(object sender, EventArgs e) { pageUrl = HttpContext.Current.Request.Url.ToString(); if (pageUrl.LastIndexOf("?") > 0) { pageUrl = HttpContext.Current.Request.Url.ToString().Substring(pageUrl.LastIndexOf("/") + 1, pageUrl.LastIndexOf("?") - pageUrl.LastIndexOf("/") - 1); } else { pageUrl = HttpContext.Current.Request.Url.ToString().Substring(pageUrl.LastIndexOf("/") + 1, pageUrl.Length - pageUrl.LastIndexOf("/") - 1); } area = this.ddlArea.ClientID; HotZone = this.ddlHotZone.ClientID; Product = this.ddlProduct.ClientID; Square = this.ddlSquare.ClientID; HairStyle = ddlHairStyle.ClientID; FaceStyle = ddlFaceStyle.ClientID; Temperament = ddlTemperament.ClientID; Occasion = ddlOccasion.ClientID; price = this.ddlPrice.ClientID; star = this.ddlStar.ClientID; if (!Page.IsPostBack) { DataHelper _DataHelper = new DataHelper(); //绑定地区 DataSet mapZoneDs = _DataHelper.ReadDb("select * from MapZone where MapZoneVisible='1' order by MapZoneID asc"); if (mapZoneDs.Tables[0].Rows.Count > 0) { for (int i = 0; i < mapZoneDs.Tables[0].Rows.Count; i++) { ddlArea.Items.Add(mapZoneDs.Tables[0].Rows[i]["MapZoneName"].ToString()); ddlArea.Items.FindByText(mapZoneDs.Tables[0].Rows[i]["MapZoneName"].ToString()).Value = mapZoneDs.Tables[0].Rows[i]["MapZoneID"].ToString(); } } //绑定商圈 DataSet hotZoneDs = _DataHelper.ReadDb("select * from HotZone where HotZoneVisible='1' order by HotZoneID asc"); if (hotZoneDs.Tables[0].Rows.Count > 0) { for (int i = 0; i < hotZoneDs.Tables[0].Rows.Count; i++) { ddlHotZone.Items.Add(hotZoneDs.Tables[0].Rows[i]["HotZoneName"].ToString()); ddlHotZone.Items.FindByText(hotZoneDs.Tables[0].Rows[i]["HotZoneName"].ToString()).Value = hotZoneDs.Tables[0].Rows[i]["HotZoneID"].ToString(); } } //主打品牌 DataSet productDs = _DataHelper.ReadDb("select * from product order by ProductID asc"); if (productDs.Tables[0].Rows.Count > 0) { for (int i = 0; i < productDs.Tables[0].Rows.Count; i++) { ddlProduct.Items.Add(productDs.Tables[0].Rows[i]["ProductName"].ToString()); ddlProduct.Items.FindByText(productDs.Tables[0].Rows[i]["ProductName"].ToString()).Value = productDs.Tables[0].Rows[i]["ProductID"].ToString(); } } //头发长度 DataSet hairStyleDs = _DataHelper.ReadDb("select * from hairstyleclassname order by id asc"); if (hairStyleDs.Tables[0].Rows.Count > 0) { for (int i = 0; i < hairStyleDs.Tables[0].Rows.Count; i++) { ddlHairStyle.Items.Add(hairStyleDs.Tables[0].Rows[i]["hairstyleclassname"].ToString()); ddlHairStyle.Items.FindByText(hairStyleDs.Tables[0].Rows[i]["hairstyleclassname"].ToString()).Value = hairStyleDs.Tables[0].Rows[i]["id"].ToString(); } } //脸型 DataSet faceStyleDs = _DataHelper.ReadDb("select * from facestyle order by id asc"); if (faceStyleDs.Tables[0].Rows.Count > 0) { for (int i = 0; i < faceStyleDs.Tables[0].Rows.Count; i++) { ddlFaceStyle.Items.Add(faceStyleDs.Tables[0].Rows[i]["facestylename"].ToString()); ddlFaceStyle.Items.FindByText(faceStyleDs.Tables[0].Rows[i]["facestylename"].ToString()).Value = faceStyleDs.Tables[0].Rows[i]["id"].ToString(); } } //气质 DataSet temperamentDs = _DataHelper.ReadDb("select * from temperament order by id asc"); if (temperamentDs.Tables[0].Rows.Count > 0) { for (int i = 0; i < temperamentDs.Tables[0].Rows.Count; i++) { ddlTemperament.Items.Add(temperamentDs.Tables[0].Rows[i]["temperament"].ToString()); ddlTemperament.Items.FindByText(temperamentDs.Tables[0].Rows[i]["temperament"].ToString()).Value = temperamentDs.Tables[0].Rows[i]["id"].ToString(); } } //场合 DataSet occasionDs = _DataHelper.ReadDb("select * from occasion order by id asc"); if (occasionDs.Tables[0].Rows.Count > 0) { for (int i = 0; i < occasionDs.Tables[0].Rows.Count; i++) { ddlOccasion.Items.Add(occasionDs.Tables[0].Rows[i]["occasion"].ToString()); ddlOccasion.Items.FindByText(occasionDs.Tables[0].Rows[i]["occasion"].ToString()).Value = occasionDs.Tables[0].Rows[i]["id"].ToString(); } } } }
protected string CheckCompany(DataHelper data, NameValueCollection nvc) { if (nvc.ContainsKey(Constants.Csource) && nvc[Constants.Csource] == Constants.CSrcCm) { if (!nvc.ContainsKey(Constants.Ccompany)) throw new ExtendedException("Company is missing", (int)Constants.EError.CompanyMissing); if (!data.CheckCompany(nvc[Constants.Ccompany])) throw new ExtendedException(String.Format("Company code [{0}] is unknown", nvc[Constants.Ccompany]), (int)Constants.EError.CompanyUnknown); return nvc[Constants.Ccompany]; } return null; }
public void FromDataTable(DataTable table, bool resetIdentity, string tableName = "") { if (tableName.IsNullOrEmpty()) { tableName = table.TableName; } var rowCount = table.Rows.Count; var sbColumnNames = new StringBuilder(); var sbColumnParamNames = new StringBuilder(); var countColumns = table.Columns.Count; var importerDB = new DataHelper(this.ConnectionString); if (resetIdentity) { importerDB.ResetIdentityInTable(new List<string>() { tableName }); } //iterate in columns for (var c = 0; c < countColumns; c++) { var column = table.Columns[c]; if (c > 0) { sbColumnNames.Append(", "); sbColumnParamNames.Append(","); } sbColumnNames.Append(column.ColumnName); sbColumnParamNames.Append(string.Format("@{0}", column.ColumnName)); } var boundColumns = new Dictionary<string, string>(); for (var r = 0; r < rowCount; r++) { var sbInsert = new StringBuilder(); var row = table.Rows[r]; //create insert statement using table and column names sbInsert.Append("INSERT into " + tableName + "(" + sbColumnNames.ToString() + ") values(" + sbColumnParamNames.ToString() + "); "); var parameters = new List<object>(); //iterate over all items in the list of bootstrap data on columns for (var cc = 0; cc < countColumns; cc++) { //take parameters from data table of sample db var currentColumn = table.Columns[cc]; parameters.Add(string.Format("@{0}", currentColumn.ColumnName)); //read from origianl value in the sequence parameters.Add(row[currentColumn.ColumnName]); } //insert data importerDB.ExecuteQuery(sbInsert.ToString(), parameters.ToArray()); } }
public ActionResult Create() { AddViewData("ListState", DataHelper.ListEnumType <StateEnum>()); return(View("Create", new MenuConfigModels())); }
private bool CheckSoldTradesParameters(SortedDictionary <string, string> parameters, out DateTime?start_time, out DateTime?end_time, out string status, out int page_no, out int page_size, ref string result) { start_time = new DateTime?(); end_time = new DateTime?(); page_size = 10; page_no = 1; status = DataHelper.CleanSearchString(parameters["status"]); if (OpenApiHelper.CheckSystemParameters(parameters, this.site.AppKey, out result)) { DateTime time2; if (!string.IsNullOrEmpty(parameters["start_created"]) && !OpenApiHelper.IsDate(parameters["start_created"])) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Invalid_Timestamp, "start_created"); return(false); } if (!string.IsNullOrEmpty(parameters["end_created"]) && !OpenApiHelper.IsDate(parameters["end_created"])) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Invalid_Timestamp, "end_created"); return(false); } if (!string.IsNullOrEmpty(parameters["start_created"])) { DateTime time; DateTime.TryParse(parameters["start_created"], out time); start_time = new DateTime?(time); if (time > DateTime.Now) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_Start_Now, "start_created and currenttime"); return(false); } if (!string.IsNullOrEmpty(parameters["end_created"])) { DateTime.TryParse(parameters["end_created"], out time2); end_time = new DateTime?(time2); if (time > time2) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_Start_End, "start_created and end_created"); return(false); } if (time2 > DateTime.Now) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_End_Now, "end_created and currenttime"); return(false); } } } else if (!string.IsNullOrEmpty(parameters["end_created"])) { DateTime.TryParse(parameters["end_created"], out time2); if (time2 > DateTime.Now) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_End_Now, "end_created and currenttime"); return(false); } } if (((!string.IsNullOrWhiteSpace(status) && (status != "WAIT_BUYER_PAY")) && ((status != "WAIT_SELLER_SEND_GOODS") && (status != "WAIT_BUYER_CONFIRM_GOODS"))) && ((status != "TRADE_CLOSED") && (status != "TRADE_FINISHED"))) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Trade_Status_is_Invalid, "status"); return(false); } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_no"])) && !int.TryParse(parameters["page_no"].ToString(), out page_no)) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Parameters_Format_Error, "page_no"); return(false); } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_no"])) && (page_no <= 0)) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Page_Size_Too_Long, "page_no"); return(false); } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_size"])) && !int.TryParse(parameters["page_size"].ToString(), out page_size)) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Parameters_Format_Error, "page_size"); return(false); } if (string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_size"])) || ((page_size > 0) && (page_size <= 100))) { return(true); } result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Page_Size_Too_Long, "page_size"); } return(false); }
/// <summary> /// After node created, solver role permissions. /// </summary> private void AddRoles(object sender, EventArgs e) { string roleIds = ";" + usRoles.Value + ";"; // Check if ACL should inherit from parent if (InheritParentPermissions) { Provider.EnsureOwnAcl(EditedNode); } else { // If node has already own ACL don't leave permissions, otherwise break inheritance if (!Provider.HasOwnACL(EditedNode)) { Provider.BreakInherintance(EditedNode, false); } } int aclId = ValidationHelper.GetInteger(EditedNode.GetValue("NodeACLID"), 0); // Get orginal ACLItems DataSet ds = Provider.GetACLItems(EditedNode.NodeID, "Operator LIKE N'R%' AND ACLID = " + aclId, null, 0, "Operator, Allowed, Denied"); // Change original values if (!DataHelper.DataSourceIsEmpty(ds)) { foreach (DataRow dr in ds.Tables[0].Rows) { string op = DataHelper.GetNotEmpty(dr["Operator"], "R"); int allowed = ValidationHelper.GetInteger(dr["Allowed"], 0); int denied = ValidationHelper.GetInteger(dr["Denied"], 0); int aclRoleId = ValidationHelper.GetInteger(op.Substring(1), 0); if (aclRoleId != 0) { // Check if read permission should be set or removed if (roleIds.Contains(";" + aclRoleId + ";")) { // Remove role from processed role and adjust permissions in database roleIds = roleIds.Replace(";" + aclRoleId + ";", ";"); allowed |= 1; } else { allowed &= 126; } Provider.SetRolePermissions(EditedNode, allowed, denied, aclRoleId); } } } // Create ACL items for new roles if (roleIds.Trim(';') != "") { // Process rest of the roles string[] roles = roleIds.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string role in roles) { Provider.SetRolePermissions(EditedNode, 1, 0, int.Parse(role)); } } }
private bool CheckIncrementSoldTradesParameters(SortedDictionary <string, string> parameters, out DateTime start_modified, out DateTime end_modified, out string status, out int page_no, out int page_size, ref string result) { start_modified = DateTime.Now; end_modified = DateTime.Now; page_size = 10; page_no = 1; status = DataHelper.CleanSearchString(parameters["status"]); if (!OpenApiHelper.CheckSystemParameters(parameters, this.site.AppKey, out result)) { return(false); } if (((!string.IsNullOrWhiteSpace(status) && (status != "WAIT_BUYER_PAY")) && ((status != "WAIT_SELLER_SEND_GOODS ") && (status != "WAIT_BUYER_CONFIRM_GOODS"))) && ((status != "TRADE_CLOSED") && (status != "TRADE_FINISHED"))) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Trade_Status_is_Invalid, "status"); return(false); } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_size"])) && !int.TryParse(parameters["page_size"].ToString(), out page_size)) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Parameters_Format_Error, "page_size"); return(false); } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_size"])) && ((page_size <= 0) || (page_size > 100))) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Page_Size_Too_Long, "page_size"); return(false); } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_no"])) && !int.TryParse(parameters["page_no"].ToString(), out page_no)) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Parameters_Format_Error, "page_no"); return(false); } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_no"])) && (page_no <= 0)) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Page_Size_Too_Long, "page_no"); return(false); } if (string.IsNullOrEmpty(parameters["start_modified"])) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Missing_Required_Arguments, "start_modified"); return(false); } if (!OpenApiHelper.IsDate(parameters["start_modified"])) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Invalid_Timestamp, "start_modified"); return(false); } DateTime.TryParse(parameters["start_modified"], out start_modified); if (start_modified > DateTime.Now) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_Start_Now, "start_modified and currenttime"); return(false); } if (string.IsNullOrEmpty(parameters["end_modified"])) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Missing_Required_Arguments, "end_modified"); return(false); } if (!OpenApiHelper.IsDate(parameters["end_modified"])) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Invalid_Timestamp, "end_modified"); return(false); } DateTime.TryParse(parameters["end_modified"], out end_modified); if (start_modified > end_modified) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_Start_End, "start_modified and end_modified"); return(false); } TimeSpan span = (TimeSpan)(end_modified - start_modified); if (span.TotalDays > 1.0) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_StartModified_AND_EndModified, "start_modified and end_modified"); return(false); } if (end_modified > DateTime.Now) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_End_Now, "end_modified and currenttime"); return(false); } return(true); }
public void RearrangeShouldReturnJson() { ////Arrange providerService.Arrange(s => s.Search(Arg.IsAny <ProviderQueryModel>())).Returns( new List <Provider> { Mapper.Map <Provider>(DataHelper.GetProvider()), Mapper.Map <Provider>(DataHelper.GetProvider()) }); ////Act var result = providerController.Rearrange(0, 1); ////Assert result.Should().BeOfType(typeof(JsonResult)); }
/// <summary> /// 获取排行榜数据 /// </summary> /// <param name="typeid">排行聚合类型</param> private static void GetRankingData(int typeid) { //获取排行榜数据 IList <CacheWealthRank> wealthRank = null; IList <CacheConsumeRank> consumeRank = null; IList <CacheScoreRank> scoreRank = null; DataSet ds = FacadeManage.aideNativeWebFacade.GetDayRankingData(typeid); switch (typeid) { case 1: wealthRank = DataHelper.ConvertDataTableToObjects <CacheWealthRank>(ds.Tables[0]); break; case 2: consumeRank = DataHelper.ConvertDataTableToObjects <CacheConsumeRank>(ds.Tables[0]); break; case 3: wealthRank = DataHelper.ConvertDataTableToObjects <CacheWealthRank>(ds.Tables[0]); consumeRank = DataHelper.ConvertDataTableToObjects <CacheConsumeRank>(ds.Tables[1]); break; case 4: scoreRank = DataHelper.ConvertDataTableToObjects <CacheScoreRank>(ds.Tables[0]); break; case 5: wealthRank = DataHelper.ConvertDataTableToObjects <CacheWealthRank>(ds.Tables[0]); scoreRank = DataHelper.ConvertDataTableToObjects <CacheScoreRank>(ds.Tables[1]); break; case 6: consumeRank = DataHelper.ConvertDataTableToObjects <CacheConsumeRank>(ds.Tables[0]); scoreRank = DataHelper.ConvertDataTableToObjects <CacheScoreRank>(ds.Tables[1]); break; case 7: wealthRank = DataHelper.ConvertDataTableToObjects <CacheWealthRank>(ds.Tables[0]); consumeRank = DataHelper.ConvertDataTableToObjects <CacheConsumeRank>(ds.Tables[1]); scoreRank = DataHelper.ConvertDataTableToObjects <CacheScoreRank>(ds.Tables[2]); break; } if (wealthRank != null && wealthRank.Count > 0) { foreach (CacheWealthRank wealth in wealthRank) { wealth.LastLogonAddress = FacadeManage.aideAccountsFacade.GetUserIP(wealth.UserID); } } if (consumeRank != null && consumeRank.Count > 0) { foreach (CacheConsumeRank consume in consumeRank) { consume.LastLogonAddress = FacadeManage.aideAccountsFacade.GetUserIP(consume.UserID); } } if (scoreRank != null && scoreRank.Count > 0) { foreach (CacheScoreRank score in scoreRank) { score.LastLogonAddress = FacadeManage.aideAccountsFacade.GetUserIP(score.UserID); } } _ajv.SetValidDataValue(true); _ajv.SetDataItem("WealthRank", wealthRank); _ajv.SetDataItem("ConsumeRank", consumeRank); _ajv.SetDataItem("ScoreRank", scoreRank); }
/// <summary> /// Mass operation button "OK" click. /// </summary> protected void btnOk_Click(object sender, EventArgs e) { string resultMessage = string.Empty; // Get where condition depending on mass action selection string where; List <string> contactIds = null; What what = (What)ValidationHelper.GetInteger(drpWhat.SelectedValue, 0); switch (what) { // All items case What.All: // Get all contacts with scores based on filter condition var contacts = GetContactsWithScore(); if (!DataHelper.DataSourceIsEmpty(contacts)) { // Get array list with IDs contactIds = DataHelper.GetUniqueValues(contacts.Tables[0], "ContactID", true); } break; // Selected items case What.Selected: // Get selected IDs from unigrid contactIds = gridElem.SelectedItems; break; } // Prepare where condition if ((contactIds != null) && (contactIds.Count > 0)) { where = SqlHelper.GetWhereCondition <int>("ContactID", contactIds, false); } else { where = "0=1"; } Action action = (Action)ValidationHelper.GetInteger(drpAction.SelectedItem.Value, 0); switch (action) { // Action 'Change status' case Action.ChangeStatus: // Get selected status ID from hidden field int statusId = ValidationHelper.GetInteger(hdnIdentifier.Value, -1); // If status ID is 0, the status will be removed if (statusId >= 0) { ContactInfoProvider.UpdateContactStatus(statusId, where); resultMessage = GetString("om.contact.massaction.statuschanged"); } break; // Action 'Add to contact group' case Action.AddToGroup: // Get contact group ID from hidden field int groupId = ValidationHelper.GetInteger(hdnIdentifier.Value, 0); if ((groupId > 0) && (contactIds != null)) { // Add each selected contact to the contact group, skip contacts that are already members of the group foreach (string item in contactIds) { int contactId = ValidationHelper.GetInteger(item, 0); if (contactId > 0) { ContactGroupMemberInfoProvider.SetContactGroupMemberInfo(groupId, contactId, ContactGroupMemberTypeEnum.Contact, MemberAddedHowEnum.Manual); } } // Get contact group to show result message with its display name ContactGroupInfo group = ContactGroupInfoProvider.GetContactGroupInfo(groupId); if (group != null) { resultMessage = string.Format(GetString("om.contact.massaction.addedtogroup"), HTMLHelper.HTMLEncode(group.ContactGroupDisplayName)); } } break; default: return; } if (!string.IsNullOrEmpty(resultMessage)) { lblInfo.Text = resultMessage; lblInfo.Visible = true; } // Reload unigrid gridElem.ResetSelection(); gridElem.ReloadData(); pnlUpdate.Update(); }
public void TestGetValidExt() { Assert.AreEqual(".jpeg", DataHelper.GetValidExt("image/jpeg", new [] { ".jpeg", ".png" })); Assert.AreEqual(".png", DataHelper.GetValidExt("image/png", new [] { ".jpg", ".png" })); Assert.AreEqual(".svg", DataHelper.GetValidExt("image/svg+xml", new [] { ".svg" })); }
/// <summary> /// Send validation request to validator and obtain result /// </summary> /// <param name="validatorParameters">Validator parameters</param> /// <returns>DataSet containing validator response</returns> private DataSet GetValidationResults(Dictionary <string, string> validationData, string parameter) { DataSet dsResponse = null; DataSet dsResult = new DataSet(); DataTable dtResponse = null; List <string> validatedUrls = validationData.Keys.ToList <string>(); Random randGen = new Random(); DataSource = dsResult; string source = null; int counter = 0; while (validatedUrls.Count > 0) { // Check if source is processed repeatedly if (source == validatedUrls[0]) { counter++; } else { counter = 0; } // Set current source to validate source = validatedUrls[0]; string cssData = validationData[source]; validatedUrls.RemoveAt(0); if (!String.IsNullOrEmpty(cssData)) { // Create web request HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ValidatorURL); req.Method = "POST"; string boundary = "---------------------------" + randGen.Next(1000000, 9999999) + randGen.Next(1000000, 9999999); req.ContentType = "multipart/form-data; boundary=" + boundary; // Set data to web request for validation byte[] data = Encoding.GetEncoding("UTF-8").GetBytes(GetRequestData(GetRequestDictionary(cssData), boundary)); req.ContentLength = data.Length; StreamWrapper writer = StreamWrapper.New(req.GetRequestStream()); writer.Write(data, 0, data.Length); writer.Close(); try { // Process server answer AddLog(String.Format(GetString("validation.css.validatingcss"), source)); StreamWrapper response = StreamWrapper.New(req.GetResponse().GetResponseStream()); if (response != null) { dsResponse = new DataSet(); dsResponse.ReadXml(response.SystemStream); } string[] currentUrlValues = parameter.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); Dictionary <string, object> parameters = new Dictionary <string, object>(); parameters["sitename"] = CMSContext.CurrentSiteName; parameters["user"] = currentUser; parameters["source"] = source; parameters["domainurl"] = currentUrlValues[0]; parameters["applicationurl"] = currentUrlValues[1]; dtResponse = DocumentValidationHelper.ProcessValidationResult(dsResponse, DocumentValidationEnum.CSS, parameters); // Check if response contain any relevant data if (!DataHelper.DataSourceIsEmpty(dtResponse)) { // Add response data to validation DataSet if (DataHelper.DataSourceIsEmpty(dsResult)) { dsResult.Tables.Add(dtResponse); } else { dsResult.Tables[0].Merge(dtResponse); } } } catch { if (counter < 5) { validatedUrls.Insert(0, source); } } finally { Thread.Sleep(ValidationDelay); } } } return(dsResult); }
/// <summary> /// OK click handler. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Check banned IP if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { ShowError(GetString("General.BannedIP")); return; } // Check input fields string email = txtEmail.Text.Trim(); string result = new Validator() .NotEmpty(email, rfvEmailRequired.ErrorMessage) .IsEmail(email, GetString("general.correctemailformat"), checkLength: true) .Result; if (!String.IsNullOrEmpty(result)) { ShowError(result); return; } // Try to create a new board BoardInfo boardInfo = null; if (BoardID == 0) { // Create new message board according to webpart properties boardInfo = new BoardInfo(BoardProperties); BoardInfoProvider.SetBoardInfo(boardInfo); // Update information on current message board BoardID = boardInfo.BoardID; // Set board-role relationship BoardRoleInfoProvider.SetBoardRoles(BoardID, BoardProperties.BoardRoles); // Set moderators BoardModeratorInfoProvider.SetBoardModerators(BoardID, BoardProperties.BoardModerators); } if (BoardID > 0) { // Check for duplicit e-mails DataSet ds = BoardSubscriptionInfoProvider.GetSubscriptions("(SubscriptionApproved <> 0) AND (SubscriptionBoardID=" + BoardID + ") AND (SubscriptionEmail='" + SqlHelper.GetSafeQueryString(email, false) + "')", null); if (!DataHelper.DataSourceIsEmpty(ds)) { ShowError(GetString("board.subscription.emailexists")); return; } BoardSubscriptionInfo bsi = new BoardSubscriptionInfo(); bsi.SubscriptionBoardID = BoardID; bsi.SubscriptionEmail = email; if ((MembershipContext.AuthenticatedUser != null) && !MembershipContext.AuthenticatedUser.IsPublic()) { bsi.SubscriptionUserID = MembershipContext.AuthenticatedUser.UserID; } BoardSubscriptionInfoProvider.Subscribe(bsi, DateTime.Now, true, true); // Clear form txtEmail.Text = ""; if (boardInfo == null) { boardInfo = BoardInfoProvider.GetBoardInfo(BoardID); } // If subscribed, log activity if (bsi.SubscriptionApproved) { ShowConfirmation(GetString("board.subscription.beensubscribed")); Service.Resolve <ICurrentContactMergeService>().UpdateCurrentContactEmail(bsi.SubscriptionEmail, MembershipContext.AuthenticatedUser); LogActivity(bsi, boardInfo); } else { string confirmation = GetString("general.subscribed.doubleoptin"); int optInInterval = BoardInfoProvider.DoubleOptInInterval(SiteContext.CurrentSiteName); if (optInInterval > 0) { confirmation += "<br />" + string.Format(GetString("general.subscription_timeintervalwarning"), optInInterval); } ShowConfirmation(confirmation); } } }
/// <summary> /// Page load. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Arguments</param> protected void Page_Load(object sender, EventArgs e) { userID = ValidationHelper.GetInteger(SessionHelper.GetValue("UserPasswordRequestID"), 0); hash = QueryHelper.GetString("hash", string.Empty); time = QueryHelper.GetString("datetime", string.Empty); policyReq = QueryHelper.GetInteger("policyreq", 0); pwdExp = QueryHelper.GetInteger("exp", 0); returnUrl = QueryHelper.GetString("returnurl", null); btnReset.Text = GetString("general.reset"); rfvConfirmPassword.Text = GetString("general.requiresvalue"); siteName = CMSContext.CurrentSiteName; // Get interval from settings interval = SettingsKeyProvider.GetDoubleValue(siteName + ".CMSResetPasswordInterval"); // Prepare failed message string invalidRequestMessage = DataHelper.GetNotEmpty(InvalidRequestText, String.Format(ResHelper.GetString("membership.passwresetfailed"), ResolveUrl("~/cmspages/logon.aspx?forgottenpassword=1"))); // Reset password cancelation if (QueryHelper.GetBoolean("cancel", false)) { // Get user info UserInfo ui = UserInfoProvider.GetUserInfoWithSettings("UserPasswordRequestHash = '" + SqlHelperClass.GetSafeQueryString(hash, true) + "'"); if (ui != null) { ui.UserPasswordRequestHash = null; UserInfoProvider.SetUserInfo(ui); SessionHelper.Remove("UserPasswordRequestID"); ShowInformation(GetString("membership.passwresetcancelled")); } else { ShowError(invalidRequestMessage); } pnlReset.Visible = false; return; } // Reset password request if (!URLHelper.IsPostback()) { if (policyReq > 0) { ShowInformation(GetString("passwordpolicy.policynotmet") + "<br />" + passStrength.GetPasswordPolicyHint()); } // Prepare query string query = "UserPasswordRequestHash = '" + SqlHelperClass.GetSafeQueryString(hash, true) + "'"; if (userID > 0) { query = SqlHelperClass.AddWhereCondition(query, "UserID = " + userID, "OR"); } // Get user info UserInfo ui = UserInfoProvider.GetUserInfoWithSettings(query); // Validate request ResetPasswordResultEnum result = AuthenticationHelper.ValidateResetPassword(ui, hash, time, interval, "Reset password control"); // Prepare messages string timeExceededMessage = DataHelper.GetNotEmpty(ExceededIntervalText, String.Format(ResHelper.GetString("membership.passwreqinterval"), ResolveUrl("~/cmspages/logon.aspx?forgottenpassword=1"))); string resultMessage = string.Empty; // Check result switch (result) { case ResetPasswordResultEnum.Success: // Save user is to session SessionHelper.SetValue("UserPasswordRequestID", ui.UserID); // Delete it from user info ui.UserPasswordRequestHash = null; UserInfoProvider.SetUserInfo(ui); break; case ResetPasswordResultEnum.TimeExceeded: resultMessage = timeExceededMessage; break; default: resultMessage = invalidRequestMessage; break; } if (!string.IsNullOrEmpty(resultMessage)) { // Show error message ShowError(resultMessage); pnlReset.Visible = false; return; } } }
/// <summary> /// Creates table. /// </summary> private void CreateTable(bool setAutomatically) { Table table = new Table(); table.GridLines = GridLines.Horizontal; table.CssClass = "UniGridGrid"; table.CellPadding = 3; table.CellSpacing = 0; table.BorderWidth = 1; // Create table header TableHeaderRow header = new TableHeaderRow(); header.HorizontalAlign = HorizontalAlign.Left; header.CssClass = "UniGridHead"; TableHeaderCell thc = new TableHeaderCell(); thc.HorizontalAlign = HorizontalAlign.Center; thc.Text = GetString("srch.settings.fieldname"); thc.Scope = TableHeaderScope.Column; thc.Style.Add("text-align", "left"); thc.Wrap = false; thc.CssClass = "ClassFieldsHeaderCell"; header.Cells.Add(thc); thc = new TableHeaderCell(); thc.Text = GetString("development.content"); thc.Scope = TableHeaderScope.Column; thc.Wrap = false; thc.CssClass = "ClassFieldsHeaderCell"; header.Cells.Add(thc); thc = new TableHeaderCell(); thc.Text = GetString("srch.settings.searchable"); thc.Scope = TableHeaderScope.Column; thc.Wrap = false; thc.CssClass = "ClassFieldsHeaderCell"; header.Cells.Add(thc); thc = new TableHeaderCell(); thc.Text = GetString("srch.settings.tokenized"); thc.Scope = TableHeaderScope.Column; thc.Wrap = false; thc.CssClass = "ClassFieldsHeaderCell"; header.Cells.Add(thc); if (DisplayIField) { thc = new TableHeaderCell(); thc.Text = GetString("srch.settings.ifield"); header.Cells.Add(thc); } thc = new TableHeaderCell(); thc.Width = Unit.Percentage(100); header.Cells.Add(thc); table.Rows.Add(header); pnlContent.Controls.Add(table); // Create table content if ((attributes != null) && (attributes.Count > 0)) { TableRow tr = null; TableCell tc = null; Label lbl = null; CheckBox chk = null; TextBox txt = null; SearchSettingsInfo ssi = null; int i = 0; // Create row for each field foreach (object[] item in attributes) { ssi = null; object[] obj = item; tr = new TableRow(); tr.CssClass = ((i % 2) == 0) ? "EvenRow" : "OddRow"; if (!DataHelper.DataSourceIsEmpty(infos)) { DataRow[] dr = infos.Tables[0].Select("name = '" + (string)obj[0] + "'"); if ((dr != null) && (dr.Length > 0) && (ss != null)) { ssi = ss.GetSettingsInfo((string)dr[0]["id"]); } } // Add cell with field name tc = new TableCell(); tc.CssClass = "ClassFieldsTableCell"; lbl = new Label(); lbl.Text = obj[0].ToString(); tc.Controls.Add(lbl); tr.Cells.Add(tc); // Add cell with 'Content' value tc = new TableCell(); tc.HorizontalAlign = HorizontalAlign.Center; chk = new CheckBox(); chk.ID = obj[0] + CONTENT; if (setAutomatically) { chk.Checked = GetPreset(CONTENT, (Type)obj[1]); } else if (ssi != null) { chk.Checked = ssi.Content; } tc.Controls.Add(chk); tr.Cells.Add(tc); // Add cell with 'Searchable' value tc = new TableCell(); tc.HorizontalAlign = HorizontalAlign.Center; chk = new CheckBox(); chk.ID = obj[0] + SEARCHABLE; if (setAutomatically) { chk.Checked = GetPreset(SEARCHABLE, (Type)obj[1]); } else if (ssi != null) { chk.Checked = ssi.Searchable; } tc.Controls.Add(chk); tr.Cells.Add(tc); // Add cell with 'Tokenized' value tc = new TableCell(); tc.HorizontalAlign = HorizontalAlign.Center; chk = new CheckBox(); chk.ID = obj[0] + TOKENIZED; if (setAutomatically) { chk.Checked = GetPreset(TOKENIZED, (Type)obj[1]); } else if (ssi != null) { chk.Checked = ssi.Tokenized; } tc.Controls.Add(chk); tr.Cells.Add(tc); // Add cell with 'iFieldname' value if (DisplayIField) { tc = new TableCell(); tc.HorizontalAlign = HorizontalAlign.Center; txt = new TextBox(); txt.ID = obj[0] + IFIELDNAME; txt.MaxLength = 200; if (ssi != null) { txt.Text = ssi.FieldName; } tc.Controls.Add(txt); tr.Cells.Add(tc); } tc = new TableCell(); tr.Cells.Add(tc); table.Rows.Add(tr); ++i; } } }
/// <summary> /// Click event of btnOk. /// </summary> /// <param name="sender">Sender</param> /// <param name="e">Arguments</param> protected void btnReset_Click(object sender, EventArgs e) { if ((passStrength.Text.Length > 0) && rfvConfirmPassword.IsValid) { if (passStrength.Text == txtConfirmPassword.Text) { // Check policy if (passStrength.IsValid()) { // Check if password expired if (pwdExp > 0) { UserInfo ui = UserInfoProvider.GetUserInfo(userID); if (!UserInfoProvider.IsUserPasswordDifferent(ui, passStrength.Text)) { ShowError(GetString("passreset.newpasswordrequired")); return; } } // Get e-mail address of sender string emailFrom = DataHelper.GetNotEmpty(SendEmailFrom, SettingsKeyProvider.GetStringValue(siteName + ".CMSSendPasswordEmailsFrom")); // Try to reset password and show result to user bool success; string resultText = AuthenticationHelper.ResetPassword(hash, time, userID, interval, passStrength.Text, "Reset password control", emailFrom, siteName, null, out success, InvalidRequestText, ExceededIntervalText, returnUrl); // If password reset was successful if (success) { SessionHelper.Remove("UserPasswordRequestID"); // Redirect to specified URL if (!string.IsNullOrEmpty(RedirectUrl)) { URLHelper.Redirect(RedirectUrl); } // Get proper text ShowConfirmation(DataHelper.GetNotEmpty(SuccessText, resultText)); pnlReset.Visible = false; lblLogonLink.Text = string.Format(GetString("memberhsip.logonlink"), returnUrl); } else { ShowError(resultText); } } else { ShowError(AuthenticationHelper.GetPolicyViolationMessage(CMSContext.CurrentSiteName)); } } else { ShowError(GetString("passreset.notmatch")); } } else { ShowError(GetString("general.requiresvalue")); } }
/// <summary> /// Gets information from XML and add it to columns. /// </summary> /// <param name="mXML">Input XML string</param> /// <returns>Return false if params is null or empty or when Xml haven't any node</returns> protected bool InitColumns(string mXML) { // Check if data are valid if (gridElem.Columns.Count > 0) { return(false); } if (string.IsNullOrEmpty(mXML)) { return(false); } if ((mColumnList == null) || (mColumnList.Length == 0)) { return(false); } // Load XML from string XmlDocument mXMLDocument = new XmlDocument(); mXMLDocument.LoadXml(mXML); XmlNodeList NodeList = mXMLDocument.DocumentElement.GetElementsByTagName("column"); if (NodeList.Count == 0) { return(false); } gridElem.AutoGenerateColumns = false; gridElem.ItemDataBound += gridElem_ItemDataBound; // Go through all nodes foreach (XmlNode node in NodeList) { string mName = XmlHelper.GetXmlAttributeValue(node.Attributes["name"], ""); string mHeader = XmlHelper.GetXmlAttributeValue(node.Attributes["header"], ""); string mType = XmlHelper.GetXmlAttributeValue(node.Attributes["type"], ""); // If name is not empty if (DataHelper.GetNotEmpty(mName, "") != "") { // And it is in the table if (IsInTable(mName)) { // Create new column DataGridColumn column = null; if ((mType != null) && (mType == "link")) { if (mGlobalNameID == null) { mGlobalNameID = new string[0]; } string[] mHelpGlobal = new string[mGlobalNameID.Length + 1]; mHelpGlobal[mGlobalNameID.Length] = mName; for (int i = 0; i < mGlobalNameID.Length; i++) { mHelpGlobal[i] = mGlobalNameID[i]; } mGlobalNameID = mHelpGlobal; TemplateColumn col = new TemplateColumn(); col.ItemTemplate = new LinkItemTemplate(mName); column = col; } else { BoundColumn col = new BoundColumn(); column = col; col.DataField = mName; } // Load header if (DataHelper.GetNotEmpty(mHeader, "") != "") { column.HeaderText = ResHelper.LocalizeString(mHeader); } else { column.HeaderText = mName; } if (gridElem.AllowSorting) { column.SortExpression = mName; } gridElem.Columns.Add(column); } } } return(true); }
private void ShowComment() { DataSet ds; DataHelper _DataHelper = new DataHelper(); int bbsid = 0; ds = _DataHelper.ReadDb("select top 1 postid from HairShop where HairShopID=" + HairShopID); if (ds.Tables[0].Rows.Count > 0) { bbsid = int.Parse(ds.Tables[0].Rows[0][0].ToString()); this.UserComment.Text = ReadComment(bbsid.ToString()).ToString(); } this.lblMoreComment.Text = "<a href=\"http://bbs.sg.com.cn/thread-"+bbsid.ToString()+"-1-1.html\" target=\"_blank\">��������>></a>"; }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { // Do nothing } else { plcOther.Controls.Clear(); if (AuthenticationHelper.IsAuthenticated()) { // Set the layout of tab menu tabMenu.TabControlLayout = BasicTabControl.GetTabMenuLayout(TabControlLayout); // Remove 'saved' parameter from query string string absoluteUri = URLHelper.RemoveParameterFromUrl(RequestContext.CurrentURL, "saved"); var currentUser = MembershipContext.AuthenticatedUser; // Get customer info GeneralizedInfo customer = null; int customerId = 0; var emptyCustomer = ModuleManager.GetReadOnlyObject(PredefinedObjectType.CUSTOMER); if (emptyCustomer != null) { var q = emptyCustomer.Generalized.GetDataQuery( true, s => s .WhereEquals("CustomerUserID", currentUser.UserID) .OrderBy("CustomerCreated") .TopN(1), false ); var result = q.Result; if (!DataHelper.DataSourceIsEmpty(result)) { customer = ModuleManager.GetObject(result.Tables[0].Rows[0], PredefinedObjectType.CUSTOMER); customerId = customer.ObjectID; } } // Get friends enabled setting bool friendsEnabled = UIHelper.IsFriendsModuleEnabled(SiteContext.CurrentSiteName); // Selected page URL string selectedPage = string.Empty; // Menu initialization tabMenu.UrlTarget = "_self"; ArrayList activeTabs = new ArrayList(); // Handle 'Notifications' tab displaying bool showNotificationsTab = (DisplayMyNotifications && LicenseHelper.IsFeatureAvailableInUI(FeatureEnum.Notifications, ModuleName.NOTIFICATIONS)); bool isWindowsAuthentication = RequestHelper.IsWindowsAuthentication(); string tabName; // Personal tab if (DisplayMyPersonalSettings) { tabName = personalTab; activeTabs.Add(tabName); tabMenu.TabItems.Add(new TabItem() { Text = GetString("MyAccount.MyPersonalSettings"), RedirectUrl = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, personalTab)) }); if (currentUser != null) { selectedPage = tabName; } } // These items can be displayed only for customer if ((customer != null) && ModuleEntryManager.IsModuleLoaded(ModuleName.ECOMMERCE)) { if (DisplayMyDetails) { // Try to load the control dynamically (if available) ucMyDetails = Page.LoadUserControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyDetails.ascx") as CMSAdminControl; if (ucMyDetails != null) { ucMyDetails.ID = "ucMyDetails"; plcOther.Controls.Add(ucMyDetails); // Set new tab tabName = detailsTab; activeTabs.Add(tabName); tabMenu.TabItems.Add(new TabItem() { Text = GetString("MyAccount.MyDetails"), RedirectUrl = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, detailsTab)) }); if (selectedPage == string.Empty) { selectedPage = tabName; } } } if (DisplayMyAddresses) { // Try to load the control dynamically (if available) ucMyAddresses = Page.LoadUserControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyAddresses.ascx") as CMSAdminControl; if (ucMyAddresses != null) { ucMyAddresses.ID = "ucMyAddresses"; plcOther.Controls.Add(ucMyAddresses); // Set new tab tabName = addressesTab; activeTabs.Add(tabName); tabMenu.TabItems.Add(new TabItem() { Text = GetString("MyAccount.MyAddresses"), RedirectUrl = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, addressesTab)) }); if (selectedPage == string.Empty) { selectedPage = tabName; } } } if (DisplayMyOrders) { // Try to load the control dynamically (if available) ucMyOrders = Page.LoadUserControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyOrders.ascx") as CMSAdminControl; if (ucMyOrders != null) { ucMyOrders.ID = "ucMyOrders"; plcOther.Controls.Add(ucMyOrders); // Set new tab tabName = ordersTab; activeTabs.Add(tabName); tabMenu.TabItems.Add(new TabItem() { Text = GetString("MyAccount.MyOrders"), RedirectUrl = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, ordersTab)) }); if (selectedPage == string.Empty) { selectedPage = tabName; } } } if (DisplayMyCredits) { // Try to load the control dynamically (if available) ucMyCredit = Page.LoadUserControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyCredit.ascx") as CMSAdminControl; if (ucMyCredit != null) { ucMyCredit.ID = "ucMyCredit"; plcOther.Controls.Add(ucMyCredit); // Set new tab tabName = creditTab; activeTabs.Add(tabName); tabMenu.TabItems.Add(new TabItem() { Text = GetString("MyAccount.MyCredit"), RedirectUrl = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, creditTab)) }); if (selectedPage == string.Empty) { selectedPage = tabName; } } } } if (DisplayChangePassword && !currentUser.IsExternal && !isWindowsAuthentication) { // Set new tab tabName = passwordTab; activeTabs.Add(tabName); tabMenu.TabItems.Add(new TabItem() { Text = GetString("MyAccount.ChangePassword"), RedirectUrl = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, passwordTab)) }); if (selectedPage == string.Empty) { selectedPage = tabName; } } if ((ucMyNotifications == null) && showNotificationsTab) { // Try to load the control dynamically (if available) ucMyNotifications = Page.LoadUserControl("~/CMSModules/Notifications/Controls/UserNotifications.ascx") as CMSAdminControl; if (ucMyNotifications != null) { ucMyNotifications.ID = "ucMyNotifications"; plcOther.Controls.Add(ucMyNotifications); // Set new tab tabName = notificationsTab; activeTabs.Add(tabName); tabMenu.TabItems.Add(new TabItem() { Text = GetString("MyAccount.MyNotifications"), RedirectUrl = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, notificationsTab)) }); if (selectedPage == string.Empty) { selectedPage = tabName; } } } if ((ucMyMessages == null) && DisplayMyMessages && ModuleManager.IsModuleLoaded(ModuleName.MESSAGING)) { // Try to load the control dynamically (if available) ucMyMessages = Page.LoadUserControl("~/CMSModules/Messaging/Controls/MyMessages.ascx") as CMSAdminControl; if (ucMyMessages != null) { ucMyMessages.ID = "ucMyMessages"; plcOther.Controls.Add(ucMyMessages); // Set new tab tabName = messagesTab; activeTabs.Add(tabName); tabMenu.TabItems.Add(new TabItem() { Text = GetString("MyAccount.MyMessages"), RedirectUrl = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, messagesTab)) }); if (selectedPage == string.Empty) { selectedPage = tabName; } } } if ((ucMyFriends == null) && DisplayMyFriends && ModuleManager.IsModuleLoaded(ModuleName.COMMUNITY) && friendsEnabled) { // Try to load the control dynamically (if available) ucMyFriends = Page.LoadUserControl("~/CMSModules/Friends/Controls/MyFriends.ascx") as CMSAdminControl; if (ucMyFriends != null) { ucMyFriends.ID = "ucMyFriends"; plcOther.Controls.Add(ucMyFriends); // Set new tab tabName = friendsTab; activeTabs.Add(tabName); tabMenu.TabItems.Add(new TabItem() { Text = GetString("MyAccount.MyFriends"), RedirectUrl = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, friendsTab)) }); if (selectedPage == string.Empty) { selectedPage = tabName; } } } if ((ucMyAllSubscriptions == null) && DisplayMySubscriptions) { // Try to load the control dynamically (if available) ucMyAllSubscriptions = Page.LoadUserControl("~/CMSModules/Membership/Controls/Subscriptions.ascx") as CMSAdminControl; if (ucMyAllSubscriptions != null) { // Set control ucMyAllSubscriptions.Visible = false; ucMyAllSubscriptions.SetValue("ShowBlogs", DisplayBlogs); ucMyAllSubscriptions.SetValue("ShowMessageBoards", DisplayMessageBoards); ucMyAllSubscriptions.SetValue("ShowNewsletters", DisplayNewsletters); ucMyAllSubscriptions.SetValue("ShowForums", DisplayForums); ucMyAllSubscriptions.SetValue("ShowReports", DisplayReports); ucMyAllSubscriptions.SetValue("sendconfirmationemail", SendConfirmationEmails); ucMyAllSubscriptions.ID = "ucMyAllSubscriptions"; plcOther.Controls.Add(ucMyAllSubscriptions); // Set new tab tabName = subscriptionsTab; activeTabs.Add(tabName); tabMenu.TabItems.Add(new TabItem() { Text = GetString("MyAccount.MyAllSubscriptions"), RedirectUrl = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, subscriptionsTab)) }); if (selectedPage == string.Empty) { selectedPage = tabName; } } } // My memberships if ((ucMyMemberships == null) && DisplayMyMemberships) { // Try to load the control dynamically ucMyMemberships = Page.LoadUserControl("~/CMSModules/Membership/Controls/MyMemberships.ascx") as CMSAdminControl; if (ucMyMemberships != null) { ucMyMemberships.SetValue("UserID", currentUser.UserID); if (!String.IsNullOrEmpty(MembershipsPagePath)) { ucMyMemberships.SetValue("BuyMembershipURL", DocumentURLProvider.GetUrl(MembershipsPagePath)); } plcOther.Controls.Add(ucMyMemberships); // Set new tab tabName = membershipsTab; activeTabs.Add(tabName); tabMenu.TabItems.Add(new TabItem() { Text = GetString("myaccount.mymemberships"), RedirectUrl = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, membershipsTab)) }); if (selectedPage == String.Empty) { selectedPage = tabName; } } } if ((ucMyCategories == null) && DisplayMyCategories) { // Try to load the control dynamically (if available) ucMyCategories = Page.LoadUserControl("~/CMSModules/Categories/Controls/Categories.ascx") as CMSAdminControl; if (ucMyCategories != null) { ucMyCategories.Visible = false; ucMyCategories.SetValue("DisplaySiteCategories", false); ucMyCategories.SetValue("DisplaySiteSelector", false); ucMyCategories.ID = "ucMyCategories"; plcOther.Controls.Add(ucMyCategories); // Set new tab tabName = categoriesTab; activeTabs.Add(tabName); tabMenu.TabItems.Add(new TabItem() { Text = GetString("MyAccount.MyCategories"), RedirectUrl = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, categoriesTab)) }); if (selectedPage == string.Empty) { selectedPage = tabName; } } } // Set CSS class pnlBody.CssClass = CssClass; // Get page URL page = QueryHelper.GetString(ParameterName, selectedPage); // Set controls visibility ucChangePassword.Visible = false; ucChangePassword.StopProcessing = true; if (ucMyAddresses != null) { ucMyAddresses.Visible = false; ucMyAddresses.StopProcessing = true; } if (ucMyOrders != null) { ucMyOrders.Visible = false; ucMyOrders.StopProcessing = true; } if (ucMyDetails != null) { ucMyDetails.Visible = false; ucMyDetails.StopProcessing = true; } if (ucMyCredit != null) { ucMyCredit.Visible = false; ucMyCredit.StopProcessing = true; } if (ucMyAllSubscriptions != null) { ucMyAllSubscriptions.Visible = false; ucMyAllSubscriptions.StopProcessing = true; ucMyAllSubscriptions.SetValue("CacheMinutes", CacheMinutes); } if (ucMyNotifications != null) { ucMyNotifications.Visible = false; ucMyNotifications.StopProcessing = true; } if (ucMyMessages != null) { ucMyMessages.Visible = false; ucMyMessages.StopProcessing = true; } if (ucMyFriends != null) { ucMyFriends.Visible = false; ucMyFriends.StopProcessing = true; } if (ucMyMemberships != null) { ucMyMemberships.Visible = false; ucMyMemberships.StopProcessing = true; } if (ucMyCategories != null) { ucMyCategories.Visible = false; ucMyCategories.StopProcessing = true; } tabMenu.SelectedTab = activeTabs.IndexOf(page); // Select current page switch (page) { case personalTab: if (myProfile != null) { // Get alternative form info AlternativeFormInfo afi = AlternativeFormInfoProvider.GetAlternativeFormInfo(AlternativeFormName); if (afi != null) { myProfile.StopProcessing = false; myProfile.Visible = true; myProfile.AllowEditVisibility = AllowEditVisibility; myProfile.AlternativeFormName = AlternativeFormName; } else { lblError.Text = String.Format(GetString("altform.formdoesntexists"), AlternativeFormName); lblError.Visible = true; myProfile.Visible = false; } } break; // My details tab case detailsTab: if (ucMyDetails != null) { ucMyDetails.Visible = true; ucMyDetails.StopProcessing = false; ucMyDetails.SetValue("Customer", customer); } break; // My addresses tab case addressesTab: if (ucMyAddresses != null) { ucMyAddresses.Visible = true; ucMyAddresses.StopProcessing = false; ucMyAddresses.SetValue("CustomerId", customerId); } break; // My orders tab case ordersTab: if (ucMyOrders != null) { ucMyOrders.Visible = true; ucMyOrders.StopProcessing = false; ucMyOrders.SetValue("CustomerId", customerId); ucMyOrders.SetValue("ShowOrderTrackingNumber", ShowOrderTrackingNumber); ucMyOrders.SetValue("ShowOrderToShoppingCart", ShowOrderToShoppingCart); } break; // My credit tab case creditTab: if (ucMyCredit != null) { ucMyCredit.Visible = true; ucMyCredit.StopProcessing = false; ucMyCredit.SetValue("CustomerId", customerId); } break; // Password tab case passwordTab: ucChangePassword.Visible = true; ucChangePassword.StopProcessing = false; ucChangePassword.AllowEmptyPassword = AllowEmptyPassword; break; // Notification tab case notificationsTab: if (ucMyNotifications != null) { ucMyNotifications.Visible = true; ucMyNotifications.StopProcessing = false; ucMyNotifications.SetValue("UserId", currentUser.UserID); ucMyNotifications.SetValue("UnigridImageDirectory", UnigridImageDirectory); } break; // My messages tab case messagesTab: if (ucMyMessages != null) { ucMyMessages.Visible = true; ucMyMessages.StopProcessing = false; } break; // My friends tab case friendsTab: if (ucMyFriends != null) { ucMyFriends.Visible = true; ucMyFriends.StopProcessing = false; ucMyFriends.SetValue("UserID", currentUser.UserID); } break; // My subscriptions tab case subscriptionsTab: if (ucMyAllSubscriptions != null) { ucMyAllSubscriptions.Visible = true; ucMyAllSubscriptions.StopProcessing = false; ucMyAllSubscriptions.SetValue("userid", currentUser.UserID); ucMyAllSubscriptions.SetValue("siteid", SiteContext.CurrentSiteID); } break; // My memberships tab case membershipsTab: if (ucMyMemberships != null) { ucMyMemberships.Visible = true; ucMyMemberships.StopProcessing = false; } break; // My categories tab case categoriesTab: if (ucMyCategories != null) { ucMyCategories.Visible = true; ucMyCategories.StopProcessing = false; } break; } } else { // Hide control if current user is not authenticated Visible = false; } } }
public SchemaHelper(string connectionString) { db = new DataHelper(connectionString); }
/// <summary> /// 申请信息 /// </summary> public TCPProcessCmdResults ProcessQueryQingGongYanCMD(TCPManager tcpMgr, TMSKSocket socket, TCPClientPool tcpClientPool, TCPOutPacketPool pool, int nID, byte[] data, int count, out TCPOutPacket tcpOutPacket) { tcpOutPacket = null; string cmdData = null; try { cmdData = new UTF8Encoding().GetString(data, 0, count); } catch (Exception) //解析错误 { LogManager.WriteLog(LogTypes.Error, string.Format("解析指令字符串错误, CMD={0}, Client={1}", (TCPGameServerCmds)nID, Global.GetSocketRemoteEndPoint(socket))); return(TCPProcessCmdResults.RESULT_FAILED); } try { string[] fields = cmdData.Split(':'); if (fields.Length != 1) { LogManager.WriteLog(LogTypes.Error, string.Format("指令参数个数错误, CMD={0}, Client={1}, Recv={2}", (TCPGameServerCmds)nID, Global.GetSocketRemoteEndPoint(socket), fields.Length)); return(TCPProcessCmdResults.RESULT_FAILED); } int roleID = Convert.ToInt32(fields[0]); GameClient client = GameManager.ClientMgr.FindClient(socket); if (null == client || client.ClientData.RoleID != roleID) { LogManager.WriteLog(LogTypes.Error, string.Format("根据RoleID定位GameClient对象失败, CMD={0}, Client={1}, RoleID={2}", (TCPGameServerCmds)nID, Global.GetSocketRemoteEndPoint(socket), roleID)); return(TCPProcessCmdResults.RESULT_FAILED); } int DBGrade = Convert.ToInt32(GameManager.GameConfigMgr.GetGameConfigItemStr("qinggongyan_grade", "0")); int TotalCount = Convert.ToInt32(GameManager.GameConfigMgr.GetGameConfigItemStr("qinggongyan_joincount", "0")); int JoinMoney = Convert.ToInt32(GameManager.GameConfigMgr.GetGameConfigItemStr("qinggongyan_joinmoney", "0")); String QingGongYanJoinFlag = Global.GetRoleParamByName(client, RoleParamName.QingGongYanJoinFlag); int currDay = Global.GetOffsetDay(DateTime.Now); int lastJoinDay = 0; int joinCount = 0; // day:count if (null != QingGongYanJoinFlag) { string[] strTemp = QingGongYanJoinFlag.Split(','); if (2 == strTemp.Length) { lastJoinDay = Convert.ToInt32(strTemp[0]); joinCount = Convert.ToInt32(strTemp[1]); } } if (currDay != lastJoinDay) { joinCount = 0; } string strcmd = ""; strcmd = string.Format("{0}:{1}:{2}:{3}:{4}", roleID, DBGrade, joinCount, TotalCount, JoinMoney); tcpOutPacket = TCPOutPacket.MakeTCPOutPacket(pool, strcmd, nID); return(TCPProcessCmdResults.RESULT_DATA); } catch (Exception ex) { DataHelper.WriteFormatExceptionLog(ex, "ProcessHoldQingGongYanCMD", false); } return(TCPProcessCmdResults.RESULT_FAILED); }
private void ShowBrowserHistory() { DataHelper _DataHelper = new DataHelper(); //�����������˻������ʲô DataSet ds_Temp = new DataSet(); StringBuilder Txt = new StringBuilder(); if (UserID != "") { ds_Temp = _DataHelper.ReadDb(string.Format("select top 6 HairShopID,HairShopName,HairShopDiscount from HairShop where HairShopID in (select ProductID from History where UserID in (select UserID from History where UserID<>{0} and ProductID={1} ) and ProductID <> {1}) ", UserID, HairShopID)); } else { ds_Temp = _DataHelper.ReadDb(string.Format("select top 6 HairShopID,HairShopName,HairShopDiscount from HairShop where HairShopID in (select ProductID from History where UserID in (select UserID from History where ProductID={1} ))", UserID, HairShopID)); } Txt = new System.Text.StringBuilder(); Txt.AppendFormat("<table width=\"92%\" border=\"0\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\" style=\"margin-top:5px\">"); foreach (DataRow thisPicRow in ds_Temp.Tables[0].Rows) { Txt.AppendFormat("<tr>"); Txt.AppendFormat(" <td width=\"83%\" align=\"left\" class=\"gray14-e\">�� <a href=\"HairShopContent.aspx?id={0}\" target=\"_blank\">{1}</a></td>", thisPicRow["HairShopID"].ToString(), StringHelper.GetDescription(thisPicRow["HairShopName"].ToString(), 12)); Txt.AppendFormat(" <td width=\"17%\" align=\"center\" class=\"red14\">{0}��</td>", thisPicRow["HairShopDiscount"].ToString()); Txt.AppendFormat("</tr>"); } Txt.AppendFormat("</table>"); this.HisBrow.Text = Txt.ToString(); }
/// <summary> /// Returns number of bounces from data row with contact data. /// </summary> private static int GetBouncesFromRow(DataRowView rowView) { return(ValidationHelper.GetInteger(DataHelper.GetDataRowValue(rowView.Row, "ContactBounces"), 0)); }
public UmbracoProviderTest() { _Helper = new DataHelper(); _Mapper = new EntityMapper(_Helper); _Provider = UmbracoProvider.GetInstance(_Mapper, "nl-NL"); }
public override List <Domain> GetDomains() { var tmp = new List <Domain>(); using (OleDbConnection _conn = new OleDbConnection(connectionString)) { _conn.Open(); using (OleDbCommand _cmd = new OleDbCommand(@"SELECT domains.id, domains.name, hosting.fp_adm, accounts.[password], clients.login, clients.passwd, dom_level_usrs.passwd AS DomainPass, domains.status AS Status, NULL AS expiration, domains.limits_id, domains.htype FROM (((((domains LEFT OUTER JOIN hosting ON hosting.dom_id = domains.id) LEFT OUTER JOIN sys_users ON hosting.sys_user_id = sys_users.id) LEFT OUTER JOIN accounts ON accounts.id = sys_users.account_id) LEFT OUTER JOIN clients ON clients.id = domains.cl_id) LEFT OUTER JOIN dom_level_usrs ON dom_level_usrs.dom_id = domains.id) ORDER BY domains.id", _conn)) { using (OleDbDataReader _read = _cmd.ExecuteReader()) { while (_read.Read()) { var _d = new Domain(); _d.Id = DataExtensions.GetColumnValue <int>(_read, "id"); _d.Name = DataExtensions.GetColumnValue <String>(_read, "name").ToLower(); _d.ClientName = DataExtensions.GetColumnValue <String>(_read, "login"); _d.DomainPassword = DataExtensions.GetColumnValue <String>(_read, "DomainPass"); _d.Username = DataExtensions.GetColumnValue <String>(_read, "fp_adm"); _d.Password = DataExtensions.GetColumnValue <String>(_read, "password"); if (String.IsNullOrEmpty(_d.Username)) { _d.Username = _d.Name; } if (String.IsNullOrEmpty(_d.Password)) { _d.Password = DataHelper.GetPassword(); } _d.Status = Convert.ToInt64(DataExtensions.GetColumnValue <decimal>(_read, "Status")); var limitId = DataExtensions.GetColumnValue <int>(_read, "limits_id"); _d.Expiration = GetExpirationDate(limitId); var hostingType = DataExtensions.GetColumnValue <String>(_read, "htype"); _d.isForwarding = (hostingType == "std_fwd" || hostingType == "frm_fwd"); if (_d.isForwarding) { var frw = GetForwarding(_d.Name); _d.ForwardUrl = frw.ForwardUrl; } _d.Aliases = GetDomainAliases(_d.Name); _d.Databases = GetDatabases(_d.Name); _d.Limits = GetDomainLimits(_d.Name); _d.Subdomains = GetSubdomains(_d.Name); _d.Zone = GetDnsZone(_d.Name); _d.Emails = GetEmails(_d.Name); tmp.Add(_d); } } } _conn.Close(); } return(tmp); }
private void WriteHistoy(int type) { //��¼��ʷ if (UserID != "") { //�Ѿ���½�ż�¼ DataHelper _DataHelper = new DataHelper(); DataSet ds = _DataHelper.ReadDb(string.Format("select * from History where UserID={0} and ProductID={1} and type={2}", UserID, HairShopID, type)); if (ds.Tables[0].Rows.Count == 0) { using (SqlConnection conn = DataHelper.ConnString()) { try { string Sql = string.Format("insert dbo.History (UserID,HistoryUrl,ProductID,UserName,type) values({0},'{1}',{2},'{3}',{4})", int.Parse(UserID), Request.Url.AbsoluteUri.ToString(), int.Parse(HairShopID), UserName, type); SqlHelper.ExecuteNonQuery(conn, CommandType.Text, Sql); } catch { } finally { if (conn.State != System.Data.ConnectionState.Closed) { conn.Close(); conn.Dispose(); } } } } } ShowInThisPage(type); }
protected void Page_Load(object sender, EventArgs e) { if (StopProcessing) { Visible = false; return; } // Get setting values string siteName = SiteContext.CurrentSiteName; var currentUser = MembershipContext.AuthenticatedUser; int expDays; if (AuthenticationHelper.IsAuthenticated() && AuthenticationHelper.IsPasswordExpirationEnabled(siteName, out expDays)) { int dayDiff = (DateTime.Now - currentUser.UserPasswordLastChanged).Days - expDays; int warningDays = SettingsKeyInfoProvider.GetIntValue(siteName + ".CMSPasswordExpirationWarningPeriod"); string changePwdLink = string.Format(@"<a href=""#"" onclick=""modalDialog('{0}','ChangePassword','720','350',null,null,true);"">{1}</a>", ResolveUrl("~/CMSModules/Membership/" + (IsLiveSite ? "CMSPages" : "Pages") + "/ChangePassword.aspx"), DataHelper.GetNotEmpty(ChangePasswordLinkText, GetString("passwordexpiration.changepassword"))); // Check if account password expired if (dayDiff >= 0) { lblExpText.Text = string.Format("{0}{1}{2}", ExpirationTextBefore, (ShowChangePasswordLink ? changePwdLink : ""), ExpirationTextAfter); } // Check for password expiration warning else if ((warningDays > 0) && (Math.Abs(dayDiff) <= warningDays)) { lblExpText.Text = string.Format("{0}{1}{2}", ExpirationWarningTextBefore, (ShowChangePasswordLink ? changePwdLink : ""), ExpirationWarningTextAfter); } else { Visible = false; } } else { Visible = false; } // Ensure dialog script ScriptHelper.RegisterDialogScript(Page); }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { uniView.StopProcessing = true; } else { uniView.ControlContext = ControlContext; // Document properties uniView.NestedControlsID = NestedControlsID; uniView.CacheItemName = CacheItemName; uniView.CacheDependencies = CacheDependencies; uniView.CacheMinutes = CacheMinutes; uniView.CheckPermissions = CheckPermissions; uniView.ClassNames = ClassNames; uniView.CategoryName = CategoryName; uniView.CombineWithDefaultCulture = CombineWithDefaultCulture; uniView.CultureCode = CultureCode; uniView.MaxRelativeLevel = MaxRelativeLevel; uniView.OrderBy = OrderBy; uniView.SelectTopN = SelectTopN; uniView.Columns = Columns; uniView.SelectOnlyPublished = SelectOnlyPublished; uniView.FilterOutDuplicates = FilterOutDuplicates; uniView.Path = Path; uniView.SiteName = SiteName; uniView.WhereCondition = WhereCondition; // CMSUniView properties uniView.LoadHierarchicalData = LoadHierarchicalData; uniView.UseHierarchicalOrder = UseHierarchicalOrder; uniView.HideHeaderAndFooterForSingleItem = HideHeaderAndFooterForSingleItem; uniView.HierarchicalDisplayMode = HierarchicalDisplayMode; uniView.DelayedLoading = DelayedLoading; // Data source settings - must be before pager settings uniView.DataSourceName = DataSourceName; uniView.DataSourceControl = DataSourceControl; // Pager uniView.LoadPagesIndividually = LoadPagesIndividually; uniView.EnablePaging = EnablePaging; uniView.PageSize = PageSize; uniView.PagerControl.QueryStringKey = QueryStringKey; uniView.PagerControl.PagerMode = PagerMode; uniView.PagerPosition = PagerPosition; uniView.PagerControl.HidePagerForSinglePage = HidePagerForSinglePage; uniView.PagerControl.GroupSize = GroupSize; uniView.PagerControl.DisplayFirstLastAutomatically = DisplayFirstLastAutomatically; uniView.PagerControl.DisplayPreviousNextAutomatically = DisplayPreviousNextAutomatically; uniView.PagerControl.ResetScrollPositionOnPostBack = ResetScrollPositionOnPostBack; // Pager transformations #region "UniPager template properties" // UniPager template properties if (!String.IsNullOrEmpty(PagesTemplate)) { uniView.PagerControl.PageNumbersTemplate = TransformationHelper.LoadTransformation(uniView.PagerControl, PagesTemplate); } if (!String.IsNullOrEmpty(CurrentPageTemplate)) { uniView.PagerControl.CurrentPageTemplate = TransformationHelper.LoadTransformation(uniView.PagerControl, CurrentPageTemplate); } if (!String.IsNullOrEmpty(SeparatorTemplate)) { uniView.PagerControl.PageNumbersSeparatorTemplate = TransformationHelper.LoadTransformation(uniView.PagerControl, SeparatorTemplate); } if (!String.IsNullOrEmpty(FirstPageTemplate)) { uniView.PagerControl.FirstPageTemplate = TransformationHelper.LoadTransformation(uniView.PagerControl, FirstPageTemplate); } if (!String.IsNullOrEmpty(LastPageTemplate)) { uniView.PagerControl.LastPageTemplate = TransformationHelper.LoadTransformation(uniView.PagerControl, LastPageTemplate); } if (!String.IsNullOrEmpty(PreviousPageTemplate)) { uniView.PagerControl.PreviousPageTemplate = TransformationHelper.LoadTransformation(uniView.PagerControl, PreviousPageTemplate); } if (!String.IsNullOrEmpty(NextPageTemplate)) { uniView.PagerControl.NextPageTemplate = TransformationHelper.LoadTransformation(uniView.PagerControl, NextPageTemplate); } if (!String.IsNullOrEmpty(PreviousGroupTemplate)) { uniView.PagerControl.PreviousGroupTemplate = TransformationHelper.LoadTransformation(uniView.PagerControl, PreviousGroupTemplate); } if (!String.IsNullOrEmpty(NextGroupTemplate)) { uniView.PagerControl.NextGroupTemplate = TransformationHelper.LoadTransformation(uniView.PagerControl, NextGroupTemplate); } if (!String.IsNullOrEmpty(DirectPageTemplate)) { uniView.PagerControl.DirectPageTemplate = TransformationHelper.LoadTransformation(uniView.PagerControl, DirectPageTemplate); } if (!String.IsNullOrEmpty(LayoutTemplate)) { uniView.PagerControl.LayoutTemplate = TransformationHelper.LoadTransformation(uniView.PagerControl, LayoutTemplate); } #endregion // Relationships uniView.RelatedNodeIsOnTheLeftSide = RelatedNodeIsOnTheLeftSide; uniView.RelationshipName = RelationshipName; uniView.RelationshipWithNodeGuid = RelationshipWithNodeGUID; // Transformation properties uniView.TransformationName = TransformationName; uniView.HierarchicalTransformationName = HierarchicalTransformationName; uniView.AlternatingTransformationName = AlternatingTransformationName; uniView.FooterTransformationName = FooterTransformationName; uniView.HeaderTransformationName = HeaderTransformationName; uniView.FirstTransformationName = FirstTransformationName; uniView.LastTransformationName = LastTransformationName; uniView.SingleTransformationName = SingleTransformationName; uniView.SeparatorTransformationName = SeparatorTransformationName; uniView.SelectedItemTransformationName = SelectedItemTransformationName; uniView.SelectedFootertemTransformationName = SelectedFooterItemTransformationName; uniView.SelectedHeaderItemTransformationName = SelectedHeaderItemTransformationName; // Public properties uniView.HideControlForZeroRows = HideControlForZeroRows; uniView.ZeroRowsText = ZeroRowsText; uniView.ItemSeparatorValue = ItemSeparator; uniView.FilterName = FilterName; // Edit mode buttons if (PageManager.ViewMode.IsLiveSite()) { btnAdd.Visible = false; uniView.ShowEditDeleteButtons = false; } else { btnAdd.Visible = ShowNewButton; btnAdd.Text = NewButtonText; uniView.ShowDeleteButton = ShowDeleteButton; uniView.ShowEditButton = ShowEditButton; } string[] mClassNames = uniView.ClassNames.Split(';'); btnAdd.ClassName = DataHelper.GetNotEmpty(mClassNames[0], ""); string mPath = ""; if (uniView.Path.EndsWithCSafe("/%")) { mPath = uniView.Path.Remove(uniView.Path.Length - 2); } if (uniView.Path.EndsWithCSafe("/")) { mPath = uniView.Path.Remove(uniView.Path.Length - 1); } btnAdd.Path = DataHelper.GetNotEmpty(mPath, ""); // Add repeater to the filter collection CMSControlsHelper.SetFilter(ValidationHelper.GetString(GetValue("WebPartControlID"), ID), uniView); if ((uniView.DataSourceControl != null) && (uniView.DataSourceControl.SourceFilterControl != null)) { uniView.DataSourceControl.SourceFilterControl.OnFilterChanged += FilterControl_OnFilterChanged; } } }
void IEdmAddIn5.OnCmd(ref EdmCmd poCmd, ref System.Array ppoData) { try { BW.RunWorkerCompleted += BW_RunWorkerCompleted; BW.WorkerSupportsCancellation = true; Debug.Print("Command Type: " + poCmd.meCmdType.ToString() + "\n " + System.DateTime.Now.ToString()); IEdmVault5 edmVault = poCmd.mpoVault as IEdmVault5; EdmCmdData[] Temp = (EdmCmdData[])ppoData; IEdmVault7 vault = (IEdmVault7)poCmd.mpoVault; vault_ = vault; try { file_ = Temp[0]; } catch { } DataHelper helper = new DataHelper(); try { switch (poCmd.meCmdType) { case EdmCmdType.EdmCmd_Menu: switch (poCmd.mlCmdID) { case 1: #region Item Master foreach (EdmCmdData file in Temp) { if (ValidSelection(file)) GetItemInfo(vault, file, ""); } #endregion break; case 2: #region Add Item/Rev/OOM/BOM string config; foreach (EdmCmdData file in Temp) { if (ValidSelection(file)) { IEdmFile5 part = (IEdmFile5)vault.GetObject(EdmObjectType.EdmObject_File, file.mlObjectID1); string selected_config = DetermineConfig(part, vault, file, ""); if (GetItemInfo(vault, file, selected_config) == DialogResult.Cancel) break; if (AddRevision(vault, file, selected_config) == DialogResult.Cancel) break; if (AddOOM(vault, file, selected_config) == DialogResult.Cancel) break; #region Bill Master BWForm = new Waiting("Retrieving Bill of Materials from SolidWorks..."); ParentNumber = ""; Area = 0; Weight = 0; Bill.Clear(); string sconfig; AddBill(vault, file, "", out sconfig); if (sconfig == null) break; Bill.Sort((x, y) => x.PartNumber.CompareTo(y.PartNumber)); CombineBill(); Bill_Master BM = new Bill_Master(Bill, ParentNumber, "", Weight, Area); #endregion if (BM.ShowDialog() == DialogResult.Cancel) break; if (CheckInPart(vault, file, selected_config) == DialogResult.Cancel) break; } } #endregion break; case 3: #region CheckOut_Master foreach (EdmCmdData file in Temp) { if (ValidSelection(file)) CheckOutPart(vault, file); } #endregion break; case 4: #region Add Revision foreach (EdmCmdData file in Temp) { if (ValidSelection(file)) AddRevision(vault, file, ""); } #endregion break; case 5: #region OOM_Master foreach (EdmCmdData file in Temp) { if (ValidSelection(file)) AddOOM(vault, file, ""); } #endregion break; case 6: #region Bill Master BWForm = new Waiting("Retrieving Bill of Materials from SolidWorks..."); foreach (EdmCmdData file in Temp) { ParentNumber = ""; Area = 0; Weight = 0; try { //BW = null; //BW = new BackgroundWorker(); Bill.Clear(); string sconfig; AddBill(vault, file, "", out sconfig); if (sconfig == null) break; Bill.Sort((x, y) => x.PartNumber.CompareTo(y.PartNumber)); CombineBill(); Bill_Master BM = new Bill_Master(Bill, ParentNumber, "", Weight, Area); BM.ShowDialog(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } #endregion break; case 7: #region CheckIn_Master foreach (EdmCmdData file in Temp) { if (ValidSelection(file)) CheckInPart(vault, file, ""); } #endregion break; case 0: #region RevCompare BWForm = new Waiting("Retrieving Bill of Materials from SolidWorks..."); foreach (EdmCmdData file in Temp) { try { string file_ext = file.mbsStrData1.Substring(file.mbsStrData1.LastIndexOf('.') + 1).ToUpper(); if (file_ext == "SLDASM") { if (file.mlObjectID1 != null) { System.Data.DataSet DS = new System.Data.DataSet(); DS.Tables.Add("PartMtl"); DS.Tables[0].Columns.Add("MtlPartNum"); DS.Tables[0].Columns.Add("QtyPer"); Bill.Clear(); ParentNumber = ""; string rconfig; AddBill(vault, file, "", out rconfig); if (rconfig == null) break; try { Bill.Sort((x, y) => x.PartNumber.CompareTo(y.PartNumber)); CombineBill(); foreach (BillItem item in Bill) { System.Data.DataRow dr = DS.Tables[0].NewRow(); dr["MtlPartNum"] = item.PartNumber; dr["QtyPer"] = item.Qty; DS.Tables[0].Rows.Add(dr); } } catch (Exception ex) { MessageBox.Show(ex.Message); } try { RevCompare RC = new RevCompare(DS, ParentNumber); RC.ShowDialog(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } else { RevCompare RC = new RevCompare(); RC.ShowDialog(); } } else { MessageBox.Show("This function cannot be used on Parts.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } break; #endregion case -2: #region Op Minutes foreach (EdmCmdData file in Temp) { try { Mins[0] = 0; //Huck Mins[1] = 0; //Tec Mins[2] = 0; //Bolt Mins[3] = 0; //Rivet Mins[4] = 0; //Band Mins[5] = 0; //Heat Mins[6] = 0; //Spring Mins[7] = 0; //Zhooks BW = null; BW = new BackgroundWorker(); BW.WorkerSupportsCancellation = true; CalcMins(vault, file, ""); Epicor_Integration.Operations_Minutes OpsMins = new Operations_Minutes(Mins[0].ToString(), Mins[1].ToString(), Mins[2].ToString(), Mins[3].ToString(), Mins[4].ToString(), Mins[5].ToString(), Mins[6].ToString(), Mins[7].ToString()); OpsMins.Show(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } break; #endregion case -1: Config conf = new Config(); conf.ShowDialog(); break; case -10: foreach (EdmCmdData file in Temp) { if (ValidSelection(file)) { Update_Properties Update = new Update_Properties(vault, file); Update.ShowDialog(); } } break; case -100: Template_Master TM = new Template_Master(); TM.ShowDialog(); break; case - 101: SearchPart SP = new SearchPart(); SP.ShowDialog(); break; default: break; } break; default: break; } } catch (COMException exp) { string errorName, errorDesc; edmVault.GetErrorString(exp.ErrorCode, out errorName, out errorDesc); edmVault.MsgBox(0, errorDesc, EdmMBoxType.EdmMbt_OKOnly, errorName); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public void SetOrientation(IO.Swagger.Model.Orientation orientation) { transform.localRotation = TransformConvertor.ROSToUnity(DataHelper.OrientationToQuaternion(orientation)); }
public SalaryAppAdapter() { _DataHelper = new DataHelper(_DBName); }
protected void Page_Load(object sender, EventArgs e) { if (StopProcessing) { return; } // Handle the pre-selection preselectedItem = QueryHelper.GetString(QueryParameterName, ""); if (preselectedItem.StartsWithCSafe("cms.", true)) { preselectedItem = preselectedItem.Substring(4); } uniMenu.HighlightItem = preselectedItem; // If element name is not set, use root module element string elemName = ElementName; if (String.IsNullOrEmpty(elemName)) { elemName = ModuleName.Replace(".", ""); } // Get the UI elements DataSet ds = UIElementInfoProvider.GetChildUIElements(ModuleName, elemName); if (!DataHelper.DataSourceIsEmpty(ds)) { FilterElements(ds); // Prepare the list of elements foreach (DataRow dr in ds.Tables[0].Rows) { string url = ValidationHelper.GetString(dr["ElementTargetURL"], ""); Group group = new Group(); if (url.EndsWithCSafe("ascx")) { group.ControlPath = url; } else { group.UIElementID = ValidationHelper.GetInteger(dr["ElementID"], 0); } group.CssClass = "ContentMenuGroup"; if (GenerateElementCssClass) { string name = ValidationHelper.GetString(dr["ElementName"], String.Empty).Replace(".", String.Empty); group.CssClass += " ContentMenuGroup" + name; group.SeparatorCssClass = "UniMenuSeparator" + name; } group.Caption = ResHelper.LocalizeString(ValidationHelper.GetString(dr["ElementCaption"], "")); uniMenu.Groups.Add(group); } // Raise groups created event if (OnGroupsCreated != null) { OnGroupsCreated(this, uniMenu.Groups); } // Button created & filtered event handler if (OnButtonCreating != null) { uniMenu.OnButtonCreating += uniMenu_OnButtonCreating; } if (OnButtonCreated != null) { uniMenu.OnButtonCreated += uniMenu_OnButtonCreated; } if (OnButtonFiltered != null) { uniMenu.OnButtonFiltered += uniMenu_OnButtonFiltered; } } // Add editing icon in development mode if (SettingsKeyProvider.DevelopmentMode && CMSContext.CurrentUser.IsGlobalAdministrator && !DisableEditIcon) { ResourceInfo ri = ResourceInfoProvider.GetResourceInfo(ModuleName); if (ri != null) { ltlAfter.Text += String.Format("<div class=\"UIElementsLink\" >{0}</div>", UIHelper.GetResourceUIElementsLink(Page, ri.ResourceId)); } } }
private void DeleteEventById(int id) { if (id <= 0) { return; } this.ClickDeleteEventInActionsColumn(id); DataHelper helper = new DataHelper(); helper.HideEventsInDeletedFolder(); }
public DataManager() { data = new DataHelper(); LoadScores(); }