protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BurrowFramework bf = new BurrowFramework(); IConversation conversation = bf.CurrentConversation; Checker.CheckSpanningConversations(0); if (conversation == null) { throw new Exception("The page doesn't have conversation"); } conversation.SpanWithPostBacks(); Checker.CheckSpanningConversations(1); Session["conversationId"] = conversation.Id; lblConversationId.Text = "Current: " + conversation.Id; WebUtil utils = new WebUtil(); frameChild.Attributes["src"] = utils.WrapUrlWithConversationInfo("Step04Child.aspx"); } }
/// <summary> /// This method is invoked by the data services framework to obtain the ETag of the stream associated with the entity specified. /// This metadata is needed when constructing the payload for the Media Link Entry associated with the stream (aka Media Resource) /// as well as to be used as the value of the ETag HTTP response header. /// </summary> /// <param name="entity">The entity associated with the stream for which an etag is to be obtained</param> /// <param name="streamProperty">Stream property instance. If it is null, the corresponding method defined on IDataServiceStreamProvider will be invoked. /// Otherwise the corresponding method defined on IDataServiceStreamProvider2 will be called with the name of the stream.</param> /// <param name="operationContext">A reference to the context for the current operation.</param> /// <returns>ETag of the stream associated with the entity specified</returns> internal string GetStreamETag(object entity, ResourceProperty streamProperty, DataServiceOperationContext operationContext) { Debug.Assert(entity != null, "entity != null"); Debug.Assert(operationContext != null, "operationContext != null"); string etag; if (streamProperty == null) { etag = InvokeApiCallAndValidateHeaders("IDataServiceStreamProvider.GetStreamETag", () => this.LoadAndValidateStreamProvider().GetStreamETag(entity, operationContext), operationContext); } else { Debug.Assert(!string.IsNullOrEmpty(streamProperty.Name), "!string.IsNullOrEmpty(stream.Name)"); etag = InvokeApiCallAndValidateHeaders("IDataServiceStreamProvider2.GetStreamETag", () => this.LoadAndValidateStreamProvider2().GetStreamETag(entity, streamProperty, operationContext), operationContext); } if (!WebUtil.IsETagValueValid(etag, true)) { throw new InvalidOperationException(Strings.DataServiceStreamProviderWrapper_GetStreamETagReturnedInvalidETagFormat); } return(etag); }
public ActionResult AddPay() { string SnNum = WebUtil.GetFormValue <string>("SnNum"); string BillNum = WebUtil.GetFormValue <string>("BillNum"); string BillSnNum = WebUtil.GetFormValue <string>("BillSnNum"); int PayType = WebUtil.GetFormValue <int>("PayType"); string BankName = WebUtil.GetFormValue <string>("BankName"); double Amount = WebUtil.GetFormValue <double>("Amount"); DateTime PayTime = WebUtil.GetFormValue <DateTime>("PayTime", DateTime.Now); FinancePayEntity entity = new FinancePayEntity(); entity.SnNum = SnNum; entity.BillSnNum = BillSnNum; entity.PayType = PayType; entity.BankName = BankName; entity.Amount = Amount; entity.PayTime = PayTime; entity.CompanyID = this.CompanyID; Dictionary <string, string> dic = new Dictionary <string, string>(); dic.Add("CompanyID", this.CompanyID); dic.Add("Entity", JsonConvert.SerializeObject(entity)); ITopClient client = new TopClientDefault(); string ApiName = FinancePayApiName.FinancePayApiName_Add; if (!SnNum.IsEmpty()) { ApiName = FinancePayApiName.FinancePayApiName_Edit; } string result = client.Execute(ApiName, dic); return(Content(result)); }
protected void ButtonExecute_Click(object sender, EventArgs e) { try { if (!WebUtil.CheckPrivilege(TheAdminServer.BatchTaskManager.SecurityObject, OpType.EXECUTE, Session)) { Response.Redirect(WebConfig.PageNotEnoughPrivilege, true); } foreach (CheckBox checkBox in _selectedCheckBox) { if (checkBox.Checked) { int taskId = int.Parse(checkBox.InputAttributes["id"]); BatchTask task = TheAdminServer.BatchTaskManager.GetBatchTask(taskId); task.Reset(); task.Start(); } } } catch (Exception) { } }
public ActionResult Add() { ITopClient client = new TopClientDefault(); string SN = WebUtil.GetFormValue <string>("SN"); string MeasureNum = WebUtil.GetFormValue <string>("MeasureNum"); string MeasureName = WebUtil.GetFormValue <string>("MeasureName"); string CompanyID = this.CompanyID; Dictionary <string, string> dic = new Dictionary <string, string>(); dic.Add("CompanyID", CompanyID); dic.Add("SN", SN); dic.Add("MeasureNum", MeasureNum); dic.Add("MeasureName", MeasureName); string ApiName = MeasureApiName.MeasureApiName_Add; if (!SN.IsEmpty()) { ApiName = MeasureApiName.MeasureApiName_Edit; } string result = client.Execute(ApiName, dic); return(Content(result)); }
private void LoadData() { hidItemCode.Value = WebUtil.Param("itemCode"); string itemCode = WebUtil.Param("itemCode"); DictionaryItem dictionaryItem = null; dictionaryItem = DictionaryItem.Retrieve(_session, itemCode); if (dictionaryItem != null) { txtCode.Text = hidItemCode.Value; txtCode.Enabled = false; txtGroupCode.Text = dictionaryItem.GroupCode; txtName.Text = dictionaryItem.Name; this.rdlItemType.Items.Clear(); EnumUtil.BindEnumData2ListControl <DictionaryItemType>(this.rdlItemType, false, dictionaryItem.ItemType); rdlItemType.SelectedValue = dictionaryItem.ItemType.ToString(); txtNumberValue.Text = Cast.String(dictionaryItem.NumberValue, "0"); txtStringValue.Value = dictionaryItem.StringValue; ddlBoolValue.SelectedValue = dictionaryItem.BoolValue.ToString(); txtNote.Value = dictionaryItem.Note; } }
public ActionResult GetList() { string StorageNum = WebUtil.GetFormValue <string>("StorageNum", string.Empty); string LocalName = WebUtil.GetFormValue <string>("LocalName", string.Empty); int LocalType = WebUtil.GetFormValue <int>("LocalType", 0); int PageIndex = WebUtil.GetFormValue <int>("PageIndex", 1); int PageSize = WebUtil.GetFormValue <int>("PageSize", 10); StorageNum = this.DefaultStorage.SnNum; ITopClient client = new TopClientDefault(); Dictionary <string, string> dic = new Dictionary <string, string>(); dic.Add("CompanyID", CompanyID); dic.Add("PageIndex", PageIndex.ToString()); dic.Add("PageSize", PageSize.ToString()); dic.Add("StorageNum", StorageNum); dic.Add("LocalName", LocalName); dic.Add("LocalType", LocalType.ToString()); string result = client.Execute(CapacityApiName.CapacityApiName_GetList, dic); return(Content(result)); }
public ActionResult DoSubmitMemberComment(string vCode) { JsResultObject re = WebUtil.DoValidateCode(vCode); if (re.code != JsResultObject.CODE_SUCCESS) { return(JsonText(re, JsonRequestBehavior.AllowGet)); } MemberModel model = this.getAuthMember(); if (model == null) { re.msg = "请先使用会员帐号登陆,再进行评论"; return(JsonText(re, JsonRequestBehavior.AllowGet)); } MemberCommentModel comment = new MemberCommentModel(); comment = WebUtil.Eval <MemberCommentModel>(comment, "", ""); comment.createDate = DateTime.Now; comment.setPk(comment.createPk()); re = BaseZdBiz.Save(comment); return(JsonText(re, JsonRequestBehavior.AllowGet)); }
public override void Process(HttpRequestArgs args) { try { if (this.SiteContext.CurrentCatalogItem != null) { return; } Sitecore.Commerce.XA.Foundation.Common.Constants.ItemTypes contextItemType = this.GetContextItemType(args.Url.ItemPath); switch (contextItemType) { case Sitecore.Commerce.XA.Foundation.Common.Constants.ItemTypes.Category: case Sitecore.Commerce.XA.Foundation.Common.Constants.ItemTypes.Product: //get the catalog item id from sku passed in query string string catalogItemIdFromUrl = this.GetCatalogItemIdFromUrl(); if (string.IsNullOrEmpty(catalogItemIdFromUrl)) { break; } bool isProduct = contextItemType == Sitecore.Commerce.XA.Foundation.Common.Constants.ItemTypes.Product; string catalog = this.StorefrontContext.CurrentStorefront.Catalog; Item obj = this.ResolveCatalogItem(catalogItemIdFromUrl, catalog, isProduct); if (obj == null) { WebUtil.Redirect("~/"); } this.SiteContext.CurrentCatalogItem = obj; break; } } catch (Exception ex) { Diagnostics.Logger.Error("Error occured found for CatalogProductItemResolver method" + ex); } }
private static void ProcessMediaDownload(HttpContext context, Database db, string itemParam) { var indexOfDot = itemParam.IndexOf(".", StringComparison.Ordinal); itemParam = indexOfDot == -1 ? itemParam : itemParam.Substring(0, indexOfDot); itemParam = itemParam.Replace('\\', '/').TrimEnd('/'); itemParam = itemParam.StartsWith("/") ? itemParam : $"/{itemParam}"; itemParam = itemParam.StartsWith(ApplicationSettings.MediaLibraryPath, StringComparison.OrdinalIgnoreCase) ? itemParam : $"{ApplicationSettings.MediaLibraryPath}{itemParam}"; var mediaItem = (MediaItem)db.GetItem(itemParam); if (mediaItem == null) { context.Response.StatusCode = 404; context.Response.StatusDescription = "The specified media is invalid."; return; } var mediaStream = mediaItem.GetMediaStream(); if (mediaStream == null) { context.Response.StatusCode = 404; context.Response.StatusDescription = "The specified media is invalid."; return; } var str = mediaItem.Extension; if (!str.StartsWith(".", StringComparison.InvariantCulture)) { str = "." + str; } AddContentHeaders(context, mediaItem.Name + str, mediaItem.Size); WebUtil.TransmitStream(mediaStream, context.Response, Settings.Media.StreamBufferSize); }
protected void Add_Click(object sender, EventArgs e) { //添加更新服务器需要在此页面上有Write的权限 if (!WebUtil.CheckPrivilege(WebConfig.FunctionUpdateServerAddUpdateServer, OpType.WRITE, Session)) { LabelOpMsg.Text = "删除服务器失败: " + StringDef.NotEnoughPrivilege; LabelOpMsg.Visible = true; return; } try { FTPServer server = new FTPServer(TextBoxServerIpAddress.Text, int.Parse(TextBoxServerPort.Text), TextBoxServerUserName.Text, TextBoxServerPassword.Text, TextBoxServerComment.Text, (FTPServer.FTPServerType)Enum.Parse(typeof(FTPServer.FTPServerType), UpdateServerTypeDropDownList.SelectedValue)); if (TheAdminServer.FTPClient.AddUpdateServer(server)) { ShowMessage(StringDef.OperationSucceed, MessageType.Success); Response.Redirect("UpdateServerConfig.aspx"); } else { throw new Exception(); } } catch (FormatException) { ShowMessage(StringDef.OperationFail + StringDef.Colon, MessageType.Failure); } catch (Exception) { ShowMessage(StringDef.OperationFail, MessageType.Failure); } }
public ActionResult Detail() { string orderNum = WebUtil.GetQueryStringValue <string>("orderNum", string.Empty); string flag = WebUtil.GetQueryStringValue <string>("flag", string.Empty); Bill <BadReportEntity, BadReportDetailEntity> bill = new BadOrder(); BadReportEntity entity = new BadReportEntity(); entity.OrderNum = orderNum; entity = bill.GetOrder(entity); entity = entity.IsNull() ? new BadReportEntity() : entity; entity.StatusLable = EnumHelper.GetEnumDesc <EAudite>(entity.Status); ViewBag.BadReport = entity; BadReportDetailEntity detail = new BadReportDetailEntity(); detail.OrderNum = orderNum; List <BadReportDetailEntity> listResult = bill.GetOrderDetail(detail); listResult = listResult.IsNull() ? new List <BadReportDetailEntity>() : listResult; ViewBag.Detail = listResult; ViewBag.Flag = flag; return(View()); }
private static void TryLogOut(IDictionary<string, string> requestParameters) { if (!requestParameters.ContainsKey("logout")) { return; } var value = requestParameters["logout"]; if (value != "true") { return; } var db = new PizzaMoreContext(); Session = WebUtil.GetSession(); var currentSession = db.Sessions.FirstOrDefault(x => x.Id == Session.Id); db.Sessions.Remove(currentSession); db.SaveChanges(); }
/// <summary> /// /// </summary> public bool CreateObject(GridRegion destination, Vector3 newPosition, ISceneObject sog, bool isLocalCall) { // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: CreateObject start"); string uri = destination.ServerURI + ObjectPath() + sog.UUID + "/"; try { OSDMap args = new OSDMap(2); args["sog"] = OSD.FromString(sog.ToXml2()); args["extra"] = OSD.FromString(sog.ExtraToXmlString()); args["modified"] = OSD.FromBoolean(sog.HasGroupChanged); args["new_position"] = newPosition.ToString(); string state = sog.GetStateSnapshot(); if (state.Length > 0) { args["state"] = OSD.FromString(state); } // Add the input general arguments args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString()); args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString()); args["destination_name"] = OSD.FromString(destination.RegionName); args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString()); WebUtil.PostToService(uri, args, 40000); } catch (Exception e) { m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] CreateObject failed with exception; {0}", e.ToString()); } return(true); }
public ActionResult Add() { string LocalNum = WebUtil.GetQueryStringValue <string>("LocalNum"); if (LocalNum.IsEmpty()) { ViewBag.Storage = LocalHelper.GetStorageNumList(string.Empty); ViewBag.LocalTypeList = EnumHelper.GetOptions <ELocalType>(string.Empty, "请选择库位类型"); ViewBag.IsDefault = EnumHelper.GetOptions <EBool>(string.Empty, "请选择"); ViewBag.Location = new LocationEntity(); } else { LocationProvider provider = new LocationProvider(); LocationEntity entity = provider.GetSingleByNum(LocalNum); entity = entity == null ? new LocationEntity() : entity; ViewBag.StorageType = EnumHelper.GetOptions <EStorageType>(entity.StorageType, "请选择仓库类型"); ViewBag.IsDefault = EnumHelper.GetOptions <EBool>(entity.IsDefault, "请选择"); ViewBag.Storage = LocalHelper.GetStorageNumList(entity.StorageNum); ViewBag.LocalTypeList = EnumHelper.GetOptions <ELocalType>(entity.LocalType, "请选择仓库类型"); ViewBag.Location = entity; } return(View()); }
protected void Edit(ClientPipelineArgs args) { Assert.ArgumentNotNull(args, "args"); if (Enabled) { if (args.IsPostBack) { if (((args.Result != null) && (args.Result.Length > 0)) && (args.Result != "undefined")) { XmlDocument doc = XmlUtil.LoadXml(WebUtil.GetSessionString("ASR_COLUMNEDITOR")); WebUtil.SetSessionValue("ASR_COLUMNEDITOR", null); Value = doc.OuterXml; SetModified(); Refresh(); } } else { XmlDocument document = GetDocument(); WebUtil.SetSessionValue("ASR_COLUMNEDITOR", document.OuterXml); UrlString urlString = new UrlString(UIUtil.GetUri("control:ColumnEditor")); UrlHandle handle = new UrlHandle(); string value = Value; if (value == "__#!$No value$!#__") { value = string.Empty; } handle["value"] = value; handle.Add(urlString); SheerResponse.ShowModalDialog(urlString.ToString(), "800px", "500px", string.Empty, true); args.WaitForPostBack(); } } }
private void deletesmstemplate(HttpContext context) { string ids = context.Request.Params["IDList"]; List <int> IDList = JsonConvert.DeserializeObject <List <int> >(ids); using (SqlHelper helper = new SqlHelper()) { try { helper.BeginTransaction(); string cmdtext = "delete from [Sms_Tencent_Template] where [ID] in (" + string.Join(",", IDList.ToArray()) + ");"; cmdtext += "delete from [Sms_Tencent_Params] where [SmsTemplateID] in (" + string.Join(",", IDList.ToArray()) + ");"; List <SqlParameter> parameters = new List <SqlParameter>(); helper.Execute(cmdtext, CommandType.Text, parameters); helper.Commit(); } catch (Exception ex) { helper.Rollback(); throw ex; } } WebUtil.WriteJson(context, new { status = true, errormsg = "OK" }); }
/// <summary> /// 取消调拨单 /// </summary> /// <returns></returns> public ActionResult Cancel() { string SnNum = WebUtil.GetFormValue <string>("SnNum"); string CompanyID = WebUtil.GetFormValue <string>("CompanyID", string.Empty); AllocateOrderEntity entity = new AllocateOrderEntity(); entity.SnNum = SnNum; entity.CompanyID = CompanyID; Bill <AllocateOrderEntity, AllocateDetailEntity> bill = new AllocateOrder(CompanyID); string returnValue = bill.Cancel(entity); DataResult result = new DataResult(); if (EnumHelper.GetEnumDesc <EReturnStatus>(EReturnStatus.Success) == returnValue) { result.Code = (int)EResponseCode.Success; result.Message = "操作成功"; } else { result.Code = (int)EResponseCode.Exception; result.Message = "操作失败"; } return(Content(JsonHelper.SerializeObject(result))); }
protected override void LoadNewPage() { WebUtil.PageSence(nowIndex, page => { if (page.Records != null && page.Records.Count > 0) { List <GameObject> list = new List <GameObject>(); item.SetActive(true); foreach (Scene scene in page.Records) { Transform clone = Instantiate(item, content).transform; clone.Find("Name").GetComponentInChildren <Text>().text = scene.Name; clone.Find("DeployTime").GetComponentInChildren <Text>().text = TimeUtil.Format(scene.DeployTime); Transform operate = clone.Find("Operate"); operate.Find("ButtonLoad").GetComponent <Button>().onClick.AddListener(delegate { BuildingUtil.Fresh(); SaveUtil.Load(scene.Id); UGUITree.current.CloseStart(); }); operate.Find("ButtonDelete").GetComponent <Button>().onClick.AddListener(delegate { }); list.Add(clone.gameObject); } item.SetActive(false); pageCache.Add(nowIndex, list); } pages = page.Pages; FreshNavigation(); }, err => { PanelLoading.current.Error(err); }); }
/// <summary> /// This is the worker function to send AgentData to a neighbor region /// </summary> private bool UpdateAgent(GridRegion destination, IAgentData cAgentData, EntityTransferContext ctx, int timeout) { // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: UpdateAgent in {0}", destination.ServerURI); // Eventually, we want to use a caps url instead of the agentID string uri = destination.ServerURI + AgentPath() + cAgentData.AgentID + "/"; try { OSDMap args = cAgentData.Pack(ctx); args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString()); args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString()); args["destination_name"] = OSD.FromString(destination.RegionName); args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString()); args["context"] = ctx.Pack(); OSDMap result = WebUtil.PutToServiceCompressed(uri, args, timeout); if (result["Success"].AsBoolean()) { return(true); } if (ctx.OutboundVersion < 0.2) { result = WebUtil.PutToService(uri, args, timeout); } return(result["Success"].AsBoolean()); } catch (Exception e) { m_log.Warn("[REMOTE SIMULATION CONNECTOR]: UpdateAgent failed with exception: " + e.ToString()); } return(false); }
public async Task SearchAsync(string query, CancellationToken ct) { var apiKey = App.Current.ApiKeys.GetKey("Octopart"); if (apiKey == null) { Debug.WriteLine("No API key available for Octopart. Searching disabled!"); return; // No API key, ignore Octopart search } // https://octopart.com/api/docs/v3/overview#datasheets query = Uri.EscapeDataString(query); var uri = new Uri(API_ENDPOINT + $"/parts/search?apikey={apiKey.SecretKey}&q={query}&start=0&limit=5&include=datasheets"); var json = await WebUtil.RequestJsonAsync <Newtonsoft.Json.Linq.JObject>(uri, ct); int hits = json.Value <int>("hits"); if (hits <= 0) { return; // No results } var results = json["results"]; //foreach (var result in results) var result = results?.First; { var description = result.Value <string>("snippet"); var item_ob = result["item"]; if (item_ob != null) { var partName = item_ob.Value <string>("mpn"); var url = item_ob.Value <string>("octopart_url"); var itemUri = new Uri(url, UriKind.Absolute); // Manufacturer info var manufacturer_ob = item_ob["manufacturer"]; var manufacturer = manufacturer_ob?.Value <string>("name"); var manufacturerUrl = manufacturer_ob?.Value <string>("homepage_url"); // Datasheets from various sources var datasheets = item_ob["datasheets"]; if (datasheets == null) { return; } foreach (var datasheet in datasheets) { var dsMimeType = datasheet.Value <string>("mimetype"); var dsUrl = datasheet.Value <string>("url"); // Metadata may or may not be present var dsMetadata = datasheet.Value <JToken>("metadata"); int?dsSize = null; int?dsPages = null; if (dsMetadata.HasValues) { dsSize = dsMetadata.Value <int>("size_bytes"); dsPages = dsMetadata.Value <int>("num_pages"); } var dsSource = datasheet.Value <JToken>("attribution")?.Value <JToken>("sources")?.First; var dsSourceName = dsSource?.Value <string>("name"); var dsUri = new Uri(dsUrl, UriKind.Absolute); //if (dsMimeType != "application/pdf") // throw new Exception($"Unsupported datasheet type {dsMimeType}"); Debug.WriteLine($"Octopart: {partName}, {url}, {manufacturer}, {dsUri}, {dsSourceName}"); OnItemFound(new OctopartSearchResult(this) { WebpageUrl = itemUri, DatasheetUrl = dsUri, PartName = partName, DatasheetSource = dsSourceName, DatasheetFileSize = dsSize, DatasheetPages = dsPages, Description = description, Manufacturer = manufacturer }); } } } return; }
public ActionResult Sendemails(SendEmailViewModel data) { StudentEmailMaster sem = new StudentEmailMaster(); sem.AcademicYear = "not defined yet";//(db.AcademicYears.FirstOrDefault().Academic_Year_En==null)? "Not defined yet": db.AcademicYears.FirstOrDefault(x => x.isCurrent == true).Academic_Year_En; sem.MailContent = HttpUtility.HtmlDecode(data.EmailBody); sem.Subject = data.Subject; string s = Regex.Replace(data.EmailBody, "<.*?>", String.Empty); sem.IsTemplate = false; sem.Type = "Sent"; sem.CreatedOn = DateTime.Now; sem.CreatedBy = (User.Identity.Name == "") ? "Naveed" : User.Identity.Name; HttpFileCollectionBase files = Request.Files; sem.IsFile = files.Count > 0 ? true : false; sem.NoFiles = files.Count; List <string> allfiles = new List <string>(); for (var i = 0; i < files.Count; i++) { HttpPostedFileBase file = files[i]; if (!string.IsNullOrEmpty(file.FileName)) { StudentEmailFile filedetail = new StudentEmailFile(); filedetail.ShowFileName = file.FileName; filedetail.FileExtnsion = file.ContentType; filedetail.URL = DateTime.Now.Ticks.ToString(); filedetail.CreatedBy = User.Identity.Name == ""?"Naveed":User.Identity.Name; filedetail.CreatedOn = DateTime.Now; filedetail.IsActive = true; string path = "/Images/" + "Mailes/" + filedetail.URL + file.FileName.LastIndexOf('.'); string createpath = "/Images/" + "Mailes/"; string dicrectory = Request.MapPath(createpath); Directory.CreateDirectory(dicrectory); string dicrectory2 = Request.MapPath(path); allfiles.Add(dicrectory2); file.SaveAs(dicrectory2); sem.StudentEmailFiles.Add(filedetail); } } foreach (var i in data.Indivisuald) { StudentEmailDetail sed = new StudentEmailDetail(); string[] a = i.Split('/'); string id = a[0]; string email = a[1]; sed.Response = "Draft"; //WebUtil.SchoolToParent(email, data.EmailBody, data.Subject, allfiles) ? "Sent" : "Failed"; sed.Email = email; sed.Date = DateTime.Now; sed.CreatedOn = DateTime.Now; sed.CreatedBy = User.Identity.Name == "" ? "Naveed" : User.Identity.Name; sem.StudentEmailDetails.Add(sed); } db.StudentEmailMasters.Add(sem); db.SaveChanges(); var detaillist = db.StudentEmailDetails.Where(x => x.MastId == sem.Id).ToList(); //deviding by int loop = 0; int skip = 0; int take = 2; string ToEmail = "*****@*****.**"; loop = detaillist.Count / 2; for (int i = 0; i < loop + 1; i++) { var skiped = detaillist.Skip(skip).Take(take).Select(x => new sendemail() { Id = x.Id, Email = x.Email }).ToList(); if (skiped.Count > 0) { var Response = WebUtil.SchoolToParent(ToEmail, skiped, data.EmailBody, data.Subject, allfiles) ? "Sent" : "Failed"; foreach (var j in detaillist.Skip(skip).Take(take)) { j.Response = Response; db.SaveChanges(); } } skip = skip + 2; } return(RedirectToAction("Index")); }
protected void Page_Load(object sender, EventArgs e) { if (string.IsNullOrEmpty(Request.QueryString["ID"])) { Response.End(); return; } int ID = 0; if (!int.TryParse(Request.QueryString["ID"], out ID)) { Response.End(); return; } var project = Project.GetProject(ID); if (project == null) { Response.End(); return; } if (project.ParentID == 1) { show_address = 1; } if (project.PrintWidth == decimal.MinValue && project.PrintHeight == decimal.MinValue) { project.PrintTitle = WebUtil.GetCompany(this.Context).CompanyName; project.CuiShouPrintTitle = WebUtil.GetCompany(this.Context).CompanyName; project.PrintFont = "100%"; project.PrintSubTitle = "收款单据"; project.CuiShouPrintSubTitle = "催费通知单"; project.IsPrintCount = true; project.IsPrintNote = true; project.IsPrintCost = true; project.IsPrintDiscount = true; project.PrintWidth = 210; project.PrintHeight = 99; using (SqlHelper helper = new SqlHelper()) { try { helper.BeginTransaction(); project.Save(helper); string commandText = @"update Project set [PrintTitle]=" + (string.IsNullOrEmpty(project.PrintTitle) ? "NULL" : "'" + project.PrintTitle + "'") + ",[PrintSubTitle]=" + (string.IsNullOrEmpty(project.PrintSubTitle) ? "NULL" : "'" + project.PrintSubTitle + "'") + ",[CuiShouPrintTitle]=" + (string.IsNullOrEmpty(project.CuiShouPrintTitle) ? "NULL" : "'" + project.CuiShouPrintTitle + "'") + ",[CuiShouPrintSubTitle]=" + (string.IsNullOrEmpty(project.CuiShouPrintSubTitle) ? "NULL" : "'" + project.CuiShouPrintSubTitle + "'") + ",[PrintFont]=" + (string.IsNullOrEmpty(project.PrintFont) ? "NULL" : "'" + project.PrintFont + "'") + ",[IsPrintNote]=1,[IsPrintCount]=1,[PrintWidth]=210,[PrintHeight]=99,[IsPrintCost]=1,[IsPrintDiscount]=1,[IsPrintRoomNo]=1 where [AllParentID] like '%," + project.ID + ",%' or [ID]=" + project.ID; List <SqlParameter> parameters = new List <SqlParameter>(); helper.Execute(commandText, CommandType.Text, parameters); helper.Commit(); } catch (Exception) { helper.Rollback(); } } } this.tdProjectName.Value = project.Name; this.tdOrderBy.Value = project.OrderBy == int.MinValue ? "" : project.OrderBy.ToString(); this.hdAddressProvice.Value = this.tdAddressProvice.Value = project.AddressProvinceID > 0 ? project.AddressProvinceID.ToString() : ""; this.hdAddressCity.Value = this.tdAddressCity.Value = project.AddressCity; this.hdAddressDistrict.Value = this.tdAddressDistrict.Value = project.AddressDistrict; }
public String Upload([In, MarshalAs(UnmanagedType.BStr)] string srvRelLibFolder, [In, MarshalAs(UnmanagedType.BStr)] string clnFullPath, [In, MarshalAs(UnmanagedType.BStr)] string srvProcessor) { //upload.exe /ServerRelPath:"drawLibs" /LocalFullPath:“C:\SmartHomeDesign_x64\2.0\drawLibs\Config.ini” /ServerProcessor:“Raw Copy” String errMsg = ""; String[] args = new String[3]; args[0] = srvRelLibFolder; args[1] = clnFullPath; args[2] = srvProcessor; Dictionary <String, String> arguments = WebUtil.getArguments(args); WebRequestSession _reqSession = new WebRequestSession(); XmlConfig.getInstance().LoadConfig("ServerInfo.xml"); Boolean ssl = (Convert.ToInt32(XmlConfig.getInstance().GetParam("server", "ssl", "1")) > 0); String textBoxServerIP = XmlConfig.getInstance().GetParam("server", "host", "localhost"); // "localhost"; String textBoxPort = XmlConfig.getInstance().GetParam("server", "port", "9443"); //"9443"; String textBoxUser = XmlConfig.getInstance().GetParam("server", "user", "admin"); //"admin"; String textBoxPass = XmlConfig.getInstance().GetParam("server", "pass", ""); //""; if (!_reqSession.Login(ssl, textBoxServerIP, Convert.ToInt32(textBoxPort), textBoxUser, textBoxPass, String.Empty, "此处放机器ID")) { Login login = new Login(); if (login.ShowDialog() == DialogResult.OK) { ssl = (Convert.ToInt32(XmlConfig.getInstance().GetParam("server", "ssl", "1")) > 0); textBoxServerIP = XmlConfig.getInstance().GetParam("server", "host", "localhost"); // "localhost"; textBoxPort = XmlConfig.getInstance().GetParam("server", "port", "9443"); //"9443"; textBoxUser = XmlConfig.getInstance().GetParam("server", "user", "admin"); //"admin"; textBoxPass = XmlConfig.getInstance().GetParam("server", "pass", ""); //""; if (!_reqSession.Login(ssl, textBoxServerIP, Convert.ToInt32(textBoxPort), textBoxUser, textBoxPass, String.Empty, "此处放机器ID")) { errMsg = "客户端登录失败"; //MessageBox.Show("客户端登录失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return(errMsg); } } else { errMsg = "客户端登录失败"; //MessageBox.Show("客户端登录失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return(errMsg); } } String IsFolder = "1"; String ServerRelPath = ""; String LocalFullPath = ""; String ServerProcessor = ""; if (arguments.ContainsKey("ServerRelPath".ToLower())) { ServerRelPath = arguments["ServerRelPath".ToLower()].Trim(); } if (arguments.ContainsKey("LocalFullPath".ToLower())) { LocalFullPath = arguments["LocalFullPath".ToLower()].Trim(); } if (arguments.ContainsKey("ServerProcessor".ToLower())) { ServerProcessor = arguments["ServerProcessor".ToLower()].Trim(); } if (arguments.ContainsKey("IsFolder".ToLower())) { IsFolder = arguments["IsFolder".ToLower()].Trim(); } if (!String.IsNullOrEmpty(LocalFullPath) && File.Exists(LocalFullPath)) { //file IsFolder = "0"; } else if (!Directory.Exists(LocalFullPath)) { //directory _reqSession.Logout(); errMsg = "本地路径无效"; //MessageBox.Show("本地路径无效", "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return(errMsg); } StringBuilder filePath = new StringBuilder(); Boolean result = RemoteCall.UploadFiles(_reqSession, IsFolder, ServerRelPath, LocalFullPath, ServerProcessor, null); _reqSession.Logout(); if (result) { //MessageBox.Show("上载成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); return(""); } errMsg = "上载失败"; //MessageBox.Show("上载失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return(errMsg); }
public static string ParseLinkUrl(IFieldValueProvider provider, string content) { string linkUrl = HtmlCommonUtil.ResolveString(provider, content); return(WebUtil.ResolveUrl(linkUrl)); }
protected void btnSave_Click(object sender, ImageClickEventArgs e) { if (drptype.SelectedValue == "-1") { jsHint.Back("请选择信息类别!"); return; } if (string.IsNullOrEmpty(txttitle.Text.Trim())) { jsHint.Back("请输入标题信息!"); return; } if (string.IsNullOrEmpty(txtorders.Text.Trim())) { jsHint.Back("请输入排序号!"); return; } if (!WebUtil.IsDigit(txtorders.Text.Trim())) { jsHint.Back("排序号请输入数字!"); return; } if (string.IsNullOrEmpty(txtcontent.Value)) { jsHint.Back("请输入内容信息!"); return; } Article addobj = new Article(); addobj.Title = txttitle.Text; addobj.Extend = loginname; addobj.Orders = string.IsNullOrEmpty(txtorders.Text) ? 0 : int.Parse(txtorders.Text); addobj.Contents = txtcontent.Value;; addobj.Description = txtsummary.Text.Trim(); addobj.Extend1 = txtkeyword.Text.Trim(); if (string.IsNullOrEmpty(txtStart.Text)) { addobj.AddTime = DateTime.Now; } else { addobj.AddTime = Convert.ToDateTime(txtStart.Text); } addobj.Status = rdisshow.SelectedValue == "0" ? 0 : 1; addobj.Type = Convert.ToInt32(drptype.SelectedValue); addobj.UpdateTime = DateTime.Now; addobj.Extend2 = loginname; if (upPic.HasFile) { string _imgpath = Guid.NewGuid().ToString() + Path.GetExtension(upPic.FileName).ToLower(); upPic.PostedFile.SaveAs(globalVariables.NewsImgPath + _imgpath); addobj.Cover = _imgpath; } else { jsHint.Back("请上传封面图片信息!"); return; } using (WXDBEntities db = new WXDBEntities()) { db.Article.AddObject(addobj); db.SaveChanges(); jsHint.toUrl("信息" + addobj.Title + "增加成功!", "SysNewsList.aspx"); } }
private void WriteObjectProperties(IExpandedResult expanded, object customObject, ResourceType resourceType, Uri parentUri, bool objectIsResource) { Debug.Assert(customObject != null, "customObject != null"); Debug.Assert(resourceType != null, "customObjectType != null"); Debug.Assert( ((customObject is IProjectedResult) && (resourceType.FullName == ((IProjectedResult)customObject).ResourceTypeName)) || (resourceType.InstanceType.IsAssignableFrom(customObject.GetType())), "The type of the object doesn't match the resource type specified."); Debug.Assert(parentUri != null, "parentUri != null"); Debug.Assert(resourceType.ResourceTypeKind != ResourceTypeKind.Primitive, "resourceType.ResourceTypeKind == ResourceTypeKind.Primitive"); // We should throw while if there are navigation properties in the derived entity type if (this.CurrentContainer != null && this.Provider.IsEntityTypeDisallowedForSet(this.CurrentContainer, resourceType)) { throw new InvalidOperationException(Strings.BaseServiceProvider_NavigationPropertiesOnDerivedEntityTypesNotSupported(resourceType.FullName, this.CurrentContainer.Name)); } IEnumerable <ProjectionNode> projectionNodes = null; if (resourceType.ResourceTypeKind == ResourceTypeKind.EntityType) { projectionNodes = this.GetProjections(); } if (projectionNodes == null) { foreach (ResourceProperty property in this.Provider.GetResourceProperties(this.CurrentContainer, resourceType)) { Debug.Assert( objectIsResource || !property.IsOfKind(ResourcePropertyKind.Key), "objectIsResource || property.Kind != ResourcePropertyKind.KeyPrimitive - complex types shouldn't have key properties"); this.WriteObjectDeclaredProperty(expanded, customObject, property, parentUri); } if (resourceType.IsOpenType) { foreach (var pair in this.Provider.GetOpenPropertyValues(customObject)) { this.WriteObjectOpenProperty(pair.Key, pair.Value, parentUri); } } } else { foreach (ProjectionNode projectionNode in projectionNodes) { string propertyName = projectionNode.PropertyName; ResourceProperty property = resourceType.TryResolvePropertyName(propertyName); if (property != null) { if (property.TypeKind != ResourceTypeKind.EntityType || this.Provider.GetResourceProperties(this.CurrentContainer, resourceType).Contains(property)) { this.WriteObjectDeclaredProperty(expanded, customObject, property, parentUri); } } else { object propertyValue = WebUtil.GetPropertyValue(this.Provider, customObject, resourceType, null, propertyName); this.WriteObjectOpenProperty(propertyName, propertyValue, parentUri); } } } }
private void WriteElementWithName(IExpandedResult expanded, object element, string elementName, Uri elementUri, bool topLevel) { Debug.Assert(elementName == null || elementName.Length > 0, "elementName == null || elementName.Length > 0"); Debug.Assert(elementUri != null, "elementUri != null"); this.RecurseEnter(); try { if (element == null) { if (topLevel) { this.writer.StartObjectScope(); this.writer.WriteName(elementName); this.WriteNullValue(); this.writer.EndScope(); } else { this.WriteNullValue(); } } else { IEnumerable enumerableElement; if (WebUtil.IsElementIEnumerable(element, out enumerableElement)) { if (this.JsonFormatVersion >= 2) { // JSON V2 Nested Collections: // { // "results": [] // "__next" : uri // } this.writer.StartObjectScope(); this.writer.WriteDataArrayName(); } this.writer.StartArrayScope(); IEnumerator elements = enumerableElement.GetEnumerator(); try { IExpandedResult expandedEnumerator = elements as IExpandedResult; object lastObject = null; IExpandedResult lastExpandedSkipToken = null; while (elements.MoveNext()) { object elementInCollection = elements.Current; IExpandedResult skipToken = this.GetSkipToken(expandedEnumerator); if (elementInCollection != null) { IExpandedResult expandedElementInCollection = elementInCollection as IExpandedResult; if (expandedElementInCollection != null) { expandedEnumerator = expandedElementInCollection; elementInCollection = GetExpandedElement(expandedEnumerator); skipToken = this.GetSkipToken(expandedEnumerator); } this.WriteElementWithName(expandedEnumerator, elementInCollection, null, elementUri, false /*topLevel*/); } lastObject = elementInCollection; lastExpandedSkipToken = skipToken; } this.writer.EndScope(); // array scope if (this.JsonFormatVersion >= 2) { // After looping through the objects in the sequence, decide if we need to write the next // page link and if yes, write it by invoking the delegate if (this.NeedNextPageLink(elements)) { this.WriteNextPageLink(lastObject, lastExpandedSkipToken, elementUri); } this.writer.EndScope(); // expanded object scope } } finally { WebUtil.Dispose(elements); } return; } ResourceType resourceType = WebUtil.GetResourceType(this.Provider, element); if (resourceType == null) { // Skip this element. return; } switch (resourceType.ResourceTypeKind) { case ResourceTypeKind.ComplexType: if (topLevel) { this.writer.StartObjectScope(); this.writer.WriteName(elementName); } // Non-value complex types may form a cycle. // PERF: we can keep a single element around and save the HashSet initialization // until we find a second complex type - this saves the allocation on trees // with shallow (single-level) complex types. if (this.AddToComplexTypeCollection(element)) { this.WriteComplexTypeProperties(element, resourceType, elementUri); this.RemoveFromComplexTypeCollection(element); } else { throw new InvalidOperationException(Strings.Serializer_LoopsNotAllowedInComplexTypes(elementName)); } if (topLevel) { this.writer.EndScope(); } break; case ResourceTypeKind.EntityType: this.IncrementSegmentResultCount(); this.writer.StartObjectScope(); Uri entityUri = Serializer.GetUri(element, this.Provider, this.CurrentContainer, this.AbsoluteServiceUri); this.WriteMetadataObject(element, resourceType, entityUri); this.WriteResourceProperties(expanded, element, resourceType, entityUri); this.writer.EndScope(); break; default: Debug.Assert(resourceType.ResourceTypeKind == ResourceTypeKind.Primitive, "resourceType.ResourceTypeKind == ResourceTypeKind.Primitive"); if (topLevel) { this.writer.StartObjectScope(); this.writer.WriteName(elementName); this.WritePrimitiveValue(element); this.writer.EndScope(); } else { this.WritePrimitiveValue(element); } break; } } } finally { // The matching call to RecurseLeave is in a try/finally block not because it's necessary in the // presence of an exception (progress will halt anyway), but because it's easier to maintain in the // code in the presence of multiple exit points (returns). this.RecurseLeave(); } }
public bool QueryAccess(GridRegion destination, UUID agentID, string agentHomeURI, bool viaTeleport, Vector3 position, string myversion, List <UUID> featuresAvailable, out string version, out string reason) { reason = "Failed to contact destination"; version = "Unknown"; // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: QueryAccess start, position={0}", position); IPEndPoint ext = destination.ExternalEndPoint; if (ext == null) { return(false); } // Eventually, we want to use a caps url instead of the agentID string uri = destination.ServerURI + AgentPath() + agentID + "/" + destination.RegionID.ToString() + "/"; OSDMap request = new OSDMap(); request.Add("viaTeleport", OSD.FromBoolean(viaTeleport)); request.Add("position", OSD.FromString(position.ToString())); request.Add("my_version", OSD.FromString(myversion)); OSDArray features = new OSDArray(); foreach (UUID feature in featuresAvailable) { features.Add(OSD.FromString(feature.ToString())); } request.Add("features", features); if (agentHomeURI != null) { request.Add("agent_home_uri", OSD.FromString(agentHomeURI)); } try { OSDMap result = WebUtil.ServiceOSDRequest(uri, request, "QUERYACCESS", 30000, false, false); bool success = result["success"].AsBoolean(); if (result.ContainsKey("_Result")) { OSDMap data = (OSDMap)result["_Result"]; // FIXME: If there is a _Result map then it's the success key here that indicates the true success // or failure, not the sibling result node. success = data["success"]; reason = data["reason"].AsString(); if (data["version"] != null && data["version"].AsString() != string.Empty) { version = data["version"].AsString(); } m_log.DebugFormat( "[REMOTE SIMULATION CONNECTOR]: QueryAccess to {0} returned {1}, reason {2}, version {3} ({4})", uri, success, reason, version, data["version"].AsString()); } if (!success) { // If we don't check this then OpenSimulator 0.7.3.1 and some period before will never see the // actual failure message if (!result.ContainsKey("_Result")) { if (result.ContainsKey("Message")) { string message = result["Message"].AsString(); if (message == "Service request failed: [MethodNotAllowed] MethodNotAllowed") // Old style region { m_log.Info("[REMOTE SIMULATION CONNECTOR]: The above web util error was caused by a TP to a sim that doesn't support QUERYACCESS and can be ignored"); return(true); } reason = result["Message"]; } else { reason = "Communications failure"; } } return(false); } featuresAvailable.Clear(); if (result.ContainsKey("features")) { OSDArray array = (OSDArray)result["features"]; foreach (OSD o in array) { featuresAvailable.Add(new UUID(o.AsString())); } } return(success); } catch (Exception e) { m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] QueryAcesss failed with exception; {0}", e.ToString()); } return(false); }
public bool CreateAgent(GridRegion source, GridRegion destination, AgentCircuitData aCircuit, uint flags, out string myipaddress, out string reason) { m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: Creating agent at {0}", destination.ServerURI); reason = String.Empty; myipaddress = String.Empty; if (destination == null) { m_log.Debug("[REMOTE SIMULATION CONNECTOR]: Given destination is null"); return(false); } string uri = destination.ServerURI + AgentPath() + aCircuit.AgentID + "/"; try { OSDMap args = aCircuit.PackAgentCircuitData(); PackData(args, source, aCircuit, destination, flags); OSDMap result = WebUtil.PostToServiceCompressed(uri, args, 30000); bool success = result["success"].AsBoolean(); if (success && result.ContainsKey("_Result")) { OSDMap data = (OSDMap)result["_Result"]; reason = data["reason"].AsString(); success = data["success"].AsBoolean(); myipaddress = data["your_ip"].AsString(); return(success); } // Try the old version, uncompressed result = WebUtil.PostToService(uri, args, 30000, false); if (result["Success"].AsBoolean()) { if (result.ContainsKey("_Result")) { OSDMap data = (OSDMap)result["_Result"]; reason = data["reason"].AsString(); success = data["success"].AsBoolean(); myipaddress = data["your_ip"].AsString(); m_log.WarnFormat( "[REMOTE SIMULATION CONNECTOR]: Remote simulator {0} did not accept compressed transfer, suggest updating it.", destination.RegionName); return(success); } } m_log.WarnFormat( "[REMOTE SIMULATION CONNECTOR]: Failed to create agent {0} {1} at remote simulator {2}", aCircuit.firstname, aCircuit.lastname, destination.RegionName); reason = result["Message"] != null ? result["Message"].AsString() : "error"; return(false); } catch (Exception e) { m_log.Warn("[REMOTE SIMULATION CONNECTOR]: CreateAgent failed with exception: " + e.ToString()); reason = e.Message; } return(false); }
/// <summary> /// Formats the literal without a type prefix, quotes, or escaping. /// </summary> /// <param name="value">The non-null value to format.</param> /// <returns>The formatted literal, without type marker or quotes.</returns> private static string FormatRawLiteral(object value) { Debug.Assert(value != null, "value != null"); string stringValue = value as string; if (stringValue != null) { return(stringValue); } if (value is bool) { return(XmlConvert.ToString((bool)value)); } if (value is byte) { return(XmlConvert.ToString((byte)value)); } #if ASTORIA_SERVER if (value is DateTime) { // Since the server/client supports DateTime values, convert the DateTime value // to DateTimeOffset and use XmlCOnvert to convert to String. DateTimeOffset dto = WebUtil.ConvertDateTimeToDateTimeOffset((DateTime)value); return(XmlConvert.ToString(dto)); } #endif if (value is decimal) { return(XmlConvert.ToString((decimal)value)); } if (value is double) { string formattedDouble = XmlConvert.ToString((double)value); formattedDouble = SharedUtils.AppendDecimalMarkerToDouble(formattedDouble); return(formattedDouble); } if (value is Guid) { return(value.ToString()); } if (value is short) { return(XmlConvert.ToString((Int16)value)); } if (value is int) { return(XmlConvert.ToString((Int32)value)); } if (value is long) { return(XmlConvert.ToString((Int64)value)); } if (value is sbyte) { return(XmlConvert.ToString((SByte)value)); } if (value is float) { return(XmlConvert.ToString((Single)value)); } byte[] array = value as byte[]; if (array != null) { return(ConvertByteArrayToKeyString(array)); } if (value is DateTimeOffset) { return(XmlConvert.ToString((DateTimeOffset)value)); } if (value is TimeSpan) { return(EdmValueWriter.DurationAsXml((TimeSpan)value)); } Geography geography = value as Geography; if (geography != null) { return(WellKnownTextSqlFormatter.Create(true).Write(geography)); } Geometry geometry = value as Geometry; if (geometry != null) { return(WellKnownTextSqlFormatter.Create(true).Write(geometry)); } throw SharedUtils.CreateExceptionForUnconvertableType(value); }