Inheritance: IServiceProvider
 /// <summary>
 /// 
 /// </summary>
 /// <param name="context"></param>
 public void ProcessRequest(HttpContext context)
 {
     try
     {
         /// this is the empy response
         string Html = string.Empty;
         /// Dictionary Collection Native Encryption
         Dictionary<string, string> Collection = cl.maia.bus.Utils.ContextForm.ProcessNativeEncryptedForm(context.Request.Form);
         /// new expando object
         string mercante = string.Empty;
         /// foreach string for the value collection
         foreach (KeyValuePair<string, string> kvp in Collection)
         {
             /// value for the parse id
             if (kvp.Key == "__m")
             {
                 mercante = kvp.Value;
             }
         }
         /// json
         string json =  JsonConvert.SerializeObject(ClientLogics.ReadPromocionesPorMercante(int.Parse(mercante)));
         /// context response
         context.Response.Write(json);
     }
     catch(Exception ex)
     {
         /// context response as an error
         context.Response.Write("{\"acknowledge\": {\"response\": \""+ex.ToString()+"\"}");
     }
 }
 public void ProcessRequest(HttpContext context)
 {
     int id = int.Parse(context.Request.QueryString["id"]);
     byte[] bytes;
     string contentType;
     string strConnString = ConfigurationManager.ConnectionStrings["dbString"].ConnectionString;
     string name;
     using (SqlConnection con = new SqlConnection(strConnString))
     {
         using (SqlCommand cmd = new SqlCommand())
         {
             cmd.CommandText = "select Name, Data, ContentType from tblFiles where Id=@Id";
             cmd.Parameters.AddWithValue("@Id", id);
             cmd.Connection = con;
             con.Open();
             SqlDataReader sdr = cmd.ExecuteReader();
             sdr.Read();
             bytes = (byte[])sdr["Data"];
             contentType = sdr["ContentType"].ToString();
             name = sdr["Name"].ToString();
             con.Close();
         }
     }
     context.Response.Clear();
     context.Response.Buffer = true;
     context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name);
     context.Response.ContentType = contentType;
     context.Response.BinaryWrite(bytes);
     context.Response.End();
 }
 internal static void DisposeHandler(HttpContext context, IntPtr nativeRequestContext, RequestNotificationStatus status)
 {
     if (UnsafeIISMethods.MgdCanDisposeManagedContext(nativeRequestContext, status))
     {
         DisposeHandlerPrivate(context);
     }
 }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            long uid = CY.Utility.Common.ConvertUtility.ConvertToLong(context.Request.QueryString["uid"], 0);

            if (uid == 0)
            {
                context.Response.Write("{success:false,msg:'活动正在统计中....'}");
                return;
            }

            CY.UME.Core.Business.Account account = CY.UME.Core.Business.Account.Load(uid);

            if (account != null)
            {
                context.Response.Write("{success:true,n:'" + account.Name + "'}");
                return;
            }
            else
            {
                context.Response.Write("{success:false,msg:'用户不存在'}");
                return;
            }
        }
 public void ProcessRequest(HttpContext context)
 {
     context.Response.ClearHeaders();
     context.Response.Clear();
     context.Response.ContentType = "text/xml";
     SerializeMetadata(context.Response.OutputStream);
 }
        public string GenerateOutput(HttpContext context, Config c)
        {
            StringBuilder sb = new StringBuilder();

            //Figure out CustomErrorsMode
            System.Configuration.Configuration configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
            CustomErrorsSection section = (configuration != null) ? section = (CustomErrorsSection)configuration.GetSection("system.web/customErrors") : null;
            CustomErrorsMode mode = (section != null) ? section.Mode : CustomErrorsMode.RemoteOnly;
            //What is diagnostics enableFor set to?
            DiagnosticMode dmode = c.get<DiagnosticMode>("diagnostics.enableFor", DiagnosticMode.None);
            //Is it set all all?
            bool diagDefined = (c.get("diagnostics.enableFor",null) != null);
            //Is it available from localhost.
            bool availLocally = (!diagDefined && mode == CustomErrorsMode.RemoteOnly) || (dmode == DiagnosticMode.Localhost);

            sb.AppendLine("The Resizer diagnostics page is " + (availLocally ? "only available from localhost." : "disabled."));
            sb.AppendLine();
            if (diagDefined) sb.AppendLine("This is because <diagnostics enableFor=\"" + dmode.ToString() + "\" />.");
            else sb.AppendLine("This is because <customErrors mode=\"" + mode.ToString() + "\" />.");
            sb.AppendLine();
            sb.AppendLine("To override for localhost access, add <diagnostics enableFor=\"localhost\" /> in the <resizer> section of Web.config.");
            sb.AppendLine();
            sb.AppendLine("To ovveride for remote access, add <diagnostics enableFor=\"allhosts\" /> in the <resizer> section of Web.config.");
            sb.AppendLine();
            return sb.ToString();
        }
Example #7
1
        public void ProcessRequest(HttpContext context)
        {
            var caller = Utilities.GetServicesAction(context);

            HandlerContainer container;
            if (!string.IsNullOrEmpty(caller.Name) && _handler.TryGetValue(caller.Name, out container))
            {
                int step = 0;
                try
                {
                    ServicesResult result = null;
                    HandlerMethodInfo mi;
                    if (container.Methods.TryGetValue(caller.Method, out mi))
                    {
                        var ticket = context.Request["__t"];
                        if (!string.IsNullOrEmpty(ticket))
                        {
                            step = 1;
                            AppContextBase.SetFormsAuthenticationTicket(ticket);
                        }
                        step = 2;
                        object obj;
                        if (mi.IsHttpContextArg && mi.ArgCount == 1)
                            obj = mi.Method.Invoke(container.Handler, new object[] { context });
                        else if (mi.ArgCount == 0)
                            obj = mi.Method.Invoke(container, null);
                        else
                            obj = mi.Method.Invoke(container, new object[mi.ArgCount]);
                        if (mi.ResultType != ServicesResult.ResultType.ServicesResultType && obj != null)
                        {
                            result = ServicesResult.GetInstance(0, "Method execute successfuly", obj);
                        }
                        else if (obj != null)
                        {
                            result = (ServicesResult)obj;
                        }
                    }
                    else
                        throw new Exception("Unkonw method info...");
                    if (result != null)
                    {
                        //context.Response.Write(result);
                        OutputResult(context, result);
                    }

                }
                catch (Exception ex)
                {
                    if (step == 1)
                        OutputResult(context, Utilities.GetWebServicesResult(-100, "你的登录已过期,请重新登录."));
                    else if (ex.InnerException != null)
                        OutputResult(context, (Utilities.GetWebServicesResult(-1, ex.InnerException.Message.Trim('\n', '\r'))));
                    else
                        OutputResult(context, (Utilities.GetWebServicesResult(-1, ex.Message.Trim('\n', '\r'))));

                }
            }
            else
                OutputResult(context, Utilities.GetWebServicesResult(-1, "Unkonw services"));
        }
Example #8
1
        public static ReturnObject Edit(HttpContext context, string name, string website = "", string phone = "", long? id = null)
        {
            Lib.Data.DrugCompany item = null;
            if (id > 0)
                item = new Lib.Data.DrugCompany(id);
            else
                item = new Lib.Data.DrugCompany();

            item.Name = name;
            item.Website = website;
            item.Phone = phone;
            item.Save();

            return new ReturnObject()
            {
                Result = item,
                Redirect = new ReturnRedirectObject()
                {
                    Hash = "admin/drugs/companies/list"
                },
                Growl = new ReturnGrowlObject()
                {
                    Type = "default",
                    Vars = new ReturnGrowlVarsObject()
                    {
                        text = "You have successfully saved this drug company.",
                        title = "Drug Company Saved"
                    }
                }
            };
        }
Example #9
1
        public static ReturnObject Delete(HttpContext context, long id)
        {
            if (id <= 0)
                return new ReturnObject() { Error = true, Message = "Invalid Drug Company." };

            var item = new Lib.Data.DrugCompany(id);
            item.Delete();

            return new ReturnObject()
            {
                Growl = new ReturnGrowlObject()
                {
                    Type = "default",
                    Vars = new ReturnGrowlVarsObject()
                    {
                        text = "You have successfully deleted a drug company.",
                        title = "Drug Company Deleted"
                    }
                },
                Actions = new List<ReturnActionObject>()
                {
                    new ReturnActionObject() {
                        Ele = "#companies-table tr[data-id=\""+id.ToString()+"\"]",
                        Type = "remove"
                    }
                }
            };
        }
Example #10
1
        protected string HandlerData(HttpContext context)
        {
            StringBuilder sbResult = new StringBuilder();
            try
            {
                string strPath = CY.Utility.Common.RequestUtility.GetQueryString("path");
                string strName = CY.Utility.Common.RequestUtility.GetQueryString("name");
                if (string.IsNullOrEmpty(strPath) || string.IsNullOrEmpty(strName))
                {
                    return sbResult.Append("{success:false,msg:'传递的参数错误ofx001!'}").ToString();
                }

                string appPath = CY.Utility.Common.RequestUtility.CurPhysicalApplicationPath;
                string dirPath = appPath + "Content\\Instrument\\Img\\";
                string fileName = strPath.Substring(strPath.LastIndexOf("/"), strPath.Length);
                if (File.Exists(dirPath + fileName))
                {
                    File.Delete(dirPath + fileName);
                    sbResult.Append("{success:true}");
                }
                else
                {
                    return sbResult.Append("{success:false,msg:'该文件件不存在!'}").ToString();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
            }
            return sbResult.ToString();
        }
        public void ProcessRequest(HttpContext context)
        {
            string username = context.Request.Params["username"];
            string password = context.Request.Params["password"];

            if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
                return;

            List<ICriterion> criterionList = new List<ICriterion>();
            criterionList.Add(Restrictions.Eq("UserName", username));
            criterionList.Add(Restrictions.Eq("Password", password));

            QueryTerms queryTerms = new QueryTerms();
            queryTerms.CriterionList = criterionList;
            queryTerms.PersistentClass = typeof(SystemUser);

            List<SystemUser> userList = (List<SystemUser>)SystemUserBll.GetSystemUserList(queryTerms, false).Data;

            string script = "";
            if (userList == null || userList.Count != 1)
            {
                script = "$('#messageSpan').html(''); setTimeout(\"$('#messageSpan').html('用户名或密码错误……');\", 50);";
            }
            else
            {
                HttpContext.Current.Session["SystemUser"] = userList[0];
                script = "location.href='Default.htm';";
            }
            context.Response.Write(script);
        }
 public override void ProcessRequest(HttpContext context)
 {
     base.ProcessRequest(context);
     context.Response.ContentType = "application/json";
     string opr = context.Request["opr"] + "";
     switch (opr)
     {
         case "addMaterialPrice"://添加
             addMaterialPrice(context);
             break;
         case "getMaterialPriceList":
             getMaterialPrice(context);
             break;
         case "getSuppliersList":
             getSuppliersList(context);
             break;
         case "getMaterialList":
             getMaterialList(context);
             break;
         case "editMaterialPrice":
             editMaterialPrice(context);
             break;
         case "delMaterialPrice":
             delMaterialPrice(context);
             break;
         case "getPriceRecord":
             getPriceRecord(context);
             break;
     }
 }
Example #13
1
        public void ProcessRequest(HttpContext context)
        {
            System.Text.StringBuilder result = new System.Text.StringBuilder();
            context.Response.ContentType = "application/json";

            try
            {
                int id;
                bool parsed = int.TryParse(context.Request.QueryString["id"], out id);

                if (!parsed)
                {
                    result.Append("{success: false, msg: '非法的标识'}");
                    context.Response.Write(result.ToString());
                    return;
                }

                CY.GeneralPrivilege.Core.Business.PermissionsList pl = CY.GeneralPrivilege.Core.Business.PermissionsList.Load(id);

                if (pl != null)
                {
                    pl.DeleteOnSave();
                    pl.Save();
                }

                result.Append("{success: true}");
            }
            catch (Exception ex)
            {
                result = new System.Text.StringBuilder();
                result.Append("{success: false, msg: '删除失败'}");
            }

            context.Response.Write(result.ToString());
        }
		public void ProcessRequest(HttpContext context)
		{
			context.Response.ContentType = "text/javascript";

			if (!context.IsDebuggingEnabled)
				context.Response.SetOutputCache(DateTime.Now.AddHours(1));

			context.Response.Write("(function (module) {");
			context.Response.Write(@"
module.factory('Translate', function () {
	return function (key, fallback) {
		var t = translations;
		var k = key.split('.');
		for (var i in k) {
			t = t[k[i]];
			if (!t) return fallback;
		}
		return t;
	}
});
");
			context.Response.Write("var translations = ");

			var jsPath = context.Request.AppRelativeCurrentExecutionFilePath.Substring(0, context.Request.AppRelativeCurrentExecutionFilePath.Length - 5);
			var file = HostingEnvironment.VirtualPathProvider.GetFile(jsPath);
			using (var s = file.Open())
			{
				TransferBetweenStreams(s, context.Response.OutputStream);
			}
			context.Response.Write(";" + Environment.NewLine);
			context.Response.Write("module.value('n2translations', translations);");

			context.Response.Write("})(angular.module('n2.localization', []));");
		}
Example #15
1
        public void ProcessRequest(HttpContext context) {
            context.Response.ContentType = "text/xml";// the data is passed in XML format

            var action = new DataAction(context.Request.Form);
            var data = new SchedulerDataContext();

            try {
                var changedEvent = (Event)DHXEventsHelper.Bind(typeof(Event), context.Request.Form);

                switch (action.Type) {
                    case DataActionTypes.Insert: // Insert logic
                        data.Events.InsertOnSubmit(changedEvent);
                        break;
                    case DataActionTypes.Delete: // Delete logic
                        changedEvent = data.Events.SingleOrDefault(ev => ev.EventID == action.SourceId);
                        data.Events.DeleteOnSubmit(changedEvent);
                        break;
                    default:// "update" // Update logic
                        var updated = data.Events.SingleOrDefault(ev => ev.EventID == action.SourceId);
                        DHXEventsHelper.Update(updated, changedEvent, new List<string>() { "EventID" });
                        break;
                }
                data.SubmitChanges();
                action.TargetId = changedEvent.EventID;
            } catch (Exception) {
                action.Type = DataActionTypes.Error;
            }

            context.Response.Write(new AjaxSaveResponse(action));
        }
 public void ProcessRequest(HttpContext context)
 {
     context.Response.ContentType = "text/plain";
     if (context.Request["mode"] != null)
     {
         string mode = context.Request["mode"].ToString();
         switch (mode)
         {
             case "inf":/*��ѯʵ����*/
                 InfoData(context);
                 break;
             case "ins":/*����*/
                 SaveData(context);
                 break;
             case "upd":/*�޸�*/
                 SaveData(context);
                 break;
             case "del":/*ɾ��*/
                 DeleteData(context);
                 break;
             case "qrycode":/*���������ѯ*/
                 QueryDataCode(context, false);
                 break;
             case "qrydate":/*�������ڲ�ѯ*/
                 QueryDataDate(context, false);
                 break;
         }
     }
 }
 public void ProcessRequest(HttpContext context)
 {
     context.Response.StatusCode = 200;
     context.Response.ContentType = "text/plain";
     context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
     context.Response.Write(GenerateOutput(context, c));
 }
Example #18
1
 public void ProcessRequest(HttpContext context)
 {
     context.Response.ContentType = "text/plain";
     context.Response.Clear();
     if (context.Request.Files.Count > 0)
     {
         try
         {
             HttpPostedFile httpPostFile = context.Request.Files[0];
             string file = context.Request.Form["Filename"].ToString();
             string fileType = file.Substring(file.LastIndexOf('.')).ToLower();
             Random r = new Random();
             string fileName = DateTime.Now.ToString("yyyyMMdd-HHmmss-ms") + r.Next(100, 999) + fileType;
             string serverPath = System.Configuration.ConfigurationSettings.AppSettings["ImageUploadPath"];
             httpPostFile.SaveAs(context.Server.MapPath(serverPath + fileName));
             context.Application["ImageUrl"] = serverPath + fileName;
             context.Response.Write("UP_OK");
         }
         catch
         {
             context.Response.Write("UP_FAILE");
         }
     }
     else
     {
         context.Response.Write("UP_FAILE");
     }
 }
        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);
            context.Response.ContentType = "application/json";
            string opr = context.Request["opr"] + "";
            switch (opr)
            {
                case "Levellist"://列表
                    getLevelList(context);
                    break;
                case "addLevel":
                    addLevel(context);
                    break;
                case "editLevel":
                    editLevel(context);
                    break;
                case "delLevel":
                    delLevel(context);
                    break;
                case "getLevelRecord"://获取调价记录
                    getLevelRecord(context);
                    break;

            }
        }
Example #20
1
        public static string SetEncoding(HttpContext context)
        {
            bool gzip, deflate;
            string encoding = "none";
            if (!string.IsNullOrEmpty(context.Request.ServerVariables["HTTP_ACCEPT_ENCODING"]))
            {
                string acceptedTypes = context.Request.ServerVariables["HTTP_ACCEPT_ENCODING"].ToLower();
                gzip = acceptedTypes.Contains("gzip") || acceptedTypes.Contains("x-gzip") || acceptedTypes.Contains("*");
                deflate = acceptedTypes.Contains("deflate");
            }
            else
                gzip = deflate = false;

            encoding = gzip ? "gzip" : (deflate ? "deflate" : "none");

            if (context.Request.Browser.Browser == "IE")
            {
                if (context.Request.Browser.MajorVersion < 6)
                    encoding = "none";
                else if (context.Request.Browser.MajorVersion == 6 &&
                    !string.IsNullOrEmpty(context.Request.ServerVariables["HTTP_USER_AGENT"]) &&
                    context.Request.ServerVariables["HTTP_USER_AGENT"].Contains("EV1"))
                    encoding = "none";
            }
            return encoding;
        }
Example #21
1
        void IHttpHandler.ProcessRequest(HttpContext httpContext)
        {
            _context = httpContext;
            var path = _context.Request.Url.AbsolutePath;
            var ext = (Path.GetExtension(path) ?? string.Empty).ToLower();

            if (Contains.Config.Image.Exts.Contains(ext))
            {
                Util.ResponseImage(_context);
                return;
            }
            var fileName = Path.GetFileNameWithoutExtension(path);
            var db = path.Split('/')[2];
            var stream = GridFsManager.Instance(db).Read(fileName);
            var hash = _context.Request.Url.AbsoluteUri.Md5();
            if (Util.IsCachedOnBrowser(_context, hash))
                return;
            var resp = _context.Response;
            resp.AppendHeader("Vary", "Accept-Encoding");
            resp.AppendHeader("Cache-Control", "max-age=604800");
            resp.AppendHeader("Expires", DateTime.Now.AddYears(1).ToString("R"));
            resp.AppendHeader("ETag", hash);
            resp.ContentType = Contains.MiniType[ext];
            resp.Charset = "utf-8";

            stream.CopyTo(resp.OutputStream);
            stream.Flush();
            stream.Close();

            resp.End();
        }
        public void ProcessRequest(HttpContext context)
        {
            NFMT.Common.UserModel user = Utility.UserUtility.CurrentUser;

            int pageIndex = 1, pageSize = 10;
            string orderStr = string.Empty, whereStr = string.Empty;

            int pledgeApplyId = 0;
            if (!string.IsNullOrEmpty(context.Request.QueryString["pid"]))
            {
                if (!int.TryParse(context.Request.QueryString["pid"], out pledgeApplyId))
                    pledgeApplyId = 0;
            }

            if (!string.IsNullOrEmpty(context.Request.QueryString["pagenum"]))
                int.TryParse(context.Request.QueryString["pagenum"], out pageIndex);
            pageIndex++;
            if (!string.IsNullOrEmpty(context.Request.QueryString["pagesize"]))
                int.TryParse(context.Request.QueryString["pagesize"], out pageSize);

            if (!string.IsNullOrEmpty(context.Request.QueryString["sortdatafield"]) && !string.IsNullOrEmpty(context.Request.QueryString["sortorder"]))
                orderStr = string.Format("{0} {1}", context.Request.QueryString["sortdatafield"].Trim(), context.Request.QueryString["sortorder"].Trim());

            FinanceService.FinService service = new FinanceService.FinService();
            string result = service.GetFinancingPledgeApplyStockDetailForHandList(pageIndex, 500, orderStr, pledgeApplyId);
            context.Response.Write(result);
        }
Example #23
1
        public void ProcessRequest(HttpContext context)
        {
            string action = context.Request.Form["Action"];

            context.Response.Clear();
            context.Response.ContentType = "application/json";
            try
            {
                switch (action)
                {
                    #region 本月账单
                    case "currentMon":
                        TradeLsit(context, action);
                        break;
                    #endregion
                    #region 全部账单
                    case "allMon":
                        TradeLsit(context, action);
                        break;
                    #endregion
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                JsonObject json = new JsonObject();
                json.Put(TAO_KEY_STATUS, TAO_STATUS_ERROR);
                json.Put(TAO_KEY_DATA, ex);
                context.Response.Write(json.ToString());
            }
        }
Example #24
0
 private void Details(HttpContext context)
 {
     int id = DTRequest.GetQueryInt("id");
     if (id < 1)
     {
         context.Response.Write("{\"status\": 0, \"msg\": \"无效的ID!\"}");
         return;
     }
     try
     {
         Model.Haulway haulway = new BLL.Haulway().GetModel(id);
         if (haulway != null)
         {
             context.Response.Write("{\"status\": 1, \"msg\": \"获取成功!\", \"name\": \"" + haulway.Name + "\", \"id\": \"" + haulway.Id + "\", \"loadingCapacityRunning\": " + haulway.LoadingCapacityRunning + ", \"noLoadingCapacityRunning\": \"" + haulway.NoLoadingCapacityRunning + "\", \"code\": \"" + haulway.Code + "\"}");
         }
         else
         {
             context.Response.Write("{\"status\": 0, \"msg\": \"记录不存在!\"}");
         }
     }
     catch
     {
         context.Response.Write("{\"status\": 0, \"msg\": \"出现异常!\"}");
         return;
     }
 }
Example #25
0
        public void ProcessRequest(HttpContext context)
        {
            string path = context.Request.QueryString["path"];

            NetworkCredential nc = GetNetCredential4Scan();

            using (
                WindowsImpersonationContextFacade impersonationContext =
                    new WindowsImpersonationContextFacade(nc))
            {
                //context.Response.Clear();
                //context.Response.ContentType = getContentType(path);

                byte[] imageByte = File.ReadAllBytes(path);

                if (imageByte != null && imageByte.Length > 0)
                {
                    context.Response.ContentType = getContentType(path);
                    context.Response.BinaryWrite(imageByte);
                }

                //context.Response.BinaryWrite(b);
                ////context.Response.WriteFile(path);
                //context.Response.End();
            }
        }
Example #26
0
 public Handler(HttpContext context)
 {
     this.Request = context.Request;
     this.Response = context.Response;
     this.Context = context;
     this.Server = context.Server;
 }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = this.ContentType;
            try
            {
                //1、检查权限,是否登录用户
                //...

                //2、动态调用方法 当然  你还可以在这里加上是否为同域名请求的判断
                this.DynamicMethod();
            }
            catch (AmbiguousMatchException amEx)
            {
                this.PrintErrorJson(string.Format("根据该参数{0}找到了多个方法", amEx.Message));
            }
            catch (ArgumentException argEx)
            {
                this.PrintErrorJson("参数异常" + argEx.Message);
            }
            catch (ApplicationException apEx)
            {
                this.PrintErrorJson("程序异常" + apEx.Message);
            }

        }
        public static string Build(HttpContext context)
        {
            if (!csFunction.ValidAdminIP(context.Request.UserHostAddress))
                return "CelebByDayGPList Fail!";

            return Build();
        }
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                var form = _factory.BuildParamsCollectionFrom(new HttpRequestWrapper(HttpContext.Current.Request));
                var serviceInstance = _container.Get(_type);

                var authorizationResult = _securityManager.Authorize<InvokeService>(serviceInstance);

                if (!authorizationResult.IsAuthorized)
                {
                    throw new HttpStatus.HttpStatusException(404, "Forbidden");
                }

                var result = _invoker.Invoke(_url, serviceInstance, context.Request.Url, form);
                context.Response.Write(result);
            }
            catch( Exception e)
            {
                if (e.InnerException != null && e.InnerException is HttpStatus.HttpStatusException)
                {
                    var ex = e.InnerException as HttpStatus.HttpStatusException;
                    context.Response.StatusCode = ex.Code;
                    context.Response.StatusDescription = ex.Description;
                }
                else
                {
                    context.Response.StatusCode = 500;
                    context.Response.StatusDescription = e.Message.Substring(0,e.Message.Length >= 512 ? 512: e.Message.Length);
                }
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.Clear();
            context.Response.AddHeader("content-disposition", "attachment; filename=SearchResult.xls");
            context.Response.ContentType = "application/ms-excel";
            context.Response.ContentEncoding = System.Text.Encoding.Unicode;
            context.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());

            var parameters = context.Request.Params;

            var data = SessionContext.Current.ExportData;
            //Convert <div><ul><li> to <table><tr><td>
            data = data.Replace("<div>", "<table><tr>").Replace("<ul", "<td rowspan='2'").Replace("<li>", String.Empty)
                       .Replace("</li>", String.Empty).Replace("</ul>", "</td>").Replace("</div>", "</tr></table>");

            // Look for invalid HTML (td inside td renders as td after td)
            data = data.Replace("<td class=\"tableColumn\">\n\t\t\t\t<td rowspan='2'>", "<td class=\"tableColumn\">");
            data = data.Replace("</td>\n\t\t\t</td>", "</td>");

            if (!String.IsNullOrEmpty(data))
            {
                var output = "<head><style>td{border:1px solid #000;}</style></head>" + data;
                context.Response.Write(output);
            }

            context.Response.End();
            SessionContext.Current.ExportData = String.Empty;
        }
Example #31
0
        /// <summary>
        /// 输出验证码表达式到浏览器
        /// </summary>
        /// <param name="context">httpcontext</param>
        /// <param name="sessionKey">保存运算值的SESSION的KEY</param>
        public void OutputImage(System.Web.HttpContext context, string sessionKey)
        {
            int    mathResult = 0;
            string expression = null;

            Random rnd = new Random();

            ////生成3个10以内的整数,用来运算
            int operator1 = rnd.Next(0, 10);
            int operator2 = rnd.Next(0, 10);
            int operator3 = rnd.Next(0, 10);

            ////随机组合运算顺序,只做 + 和 * 运算
            switch (rnd.Next(0, 3))
            {
            case 0:
                mathResult = operator1 + operator2 * operator3;
                expression = string.Format("{0} + {1} * {2} = ?", operator1, operator2, operator3);
                break;

            case 1:
                mathResult = operator1 * operator2 + operator3;
                expression = string.Format("{0} * {1} + {2} = ?", operator1, operator2, operator3);
                break;

            default:
                mathResult = operator2 + operator1 * operator3;
                expression = string.Format("{0} + {1} * {2} = ?", operator2, operator1, operator3);
                break;
            }

            using (Bitmap bmp = new Bitmap(150, 25))
            {
                using (Graphics graph = Graphics.FromImage(bmp))
                {
                    graph.Clear(Color.FromArgb(232, 238, 247)); ////背景色,可自行设置

                    ////画噪点
                    for (int i = 0; i <= 10; i++)
                    {
                        graph.DrawRectangle(
                            new Pen(Color.FromArgb(rnd.Next(0, 255), rnd.Next(0, 255), rnd.Next(0, 255))),
                            rnd.Next(2, 128),
                            rnd.Next(2, 38),
                            1,
                            1);
                    }

                    ////输出表达式
                    for (int i = 0; i < expression.Length; i++)
                    {
                        graph.DrawString(expression.Substring(i, 1),
                                         new Font(FontFamily.GenericSansSerif, 12, FontStyle.Bold),
                                         new SolidBrush(Color.FromArgb(rnd.Next(255), rnd.Next(128), rnd.Next(255))),
                                         5 + i * 10,
                                         rnd.Next(1, 5));
                    }

                    ////画边框,不需要可以注释掉
                    graph.DrawRectangle(new Pen(Color.Firebrick), 0, 0, 150 - 1, 25 - 1);
                }

                context.Session[sessionKey] = mathResult; ////将运算结果存入session

                ////禁用缓存
                //  DisableHttpCache(context);

                ////输出图片到浏览器,我采用的是 gif 格式,可自行设置其他格式
                context.Response.ContentType = "image/gif";
                bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
                context.Response.End();
            }
        }
 /// <summary>
 /// Performs any per-request initializations that the MySqlSessionStateStore provider requires.
 /// </summary>
 public override void InitializeRequest(System.Web.HttpContext context)
 {
 }
Example #33
0
        public void GetSettingPage()
        {
            DataSet _Ds;

            System.Web.HttpContext context = System.Web.HttpContext.Current;
            if (context.Request.Cookies[FormsAuthentication.FormsCookieName] == null)
            {
                //			        context.Response.Redirect("../Default.aspx");
                //					return;

                // Invalidate roles token
                context.Response.Cookies[FormsAuthentication.FormsCookieName].Value   = null;
                context.Response.Cookies[FormsAuthentication.FormsCookieName].Expires = new System.DateTime(1999, 10, 12);
                context.Response.Cookies[FormsAuthentication.FormsCookieName].Path    = "/";

                // Redirect user back to the Portal Home Page
                context.Response.Redirect(context.Request.ApplicationPath + "/Default.aspx");
                context.Response.End();
                Console.WriteLine("Entrato");
            }

            S_ControlsCollection _SCollection = new S_ControlsCollection();

            S_Controls.Collections.S_Object s_lnk = new S_Object();
            s_lnk.ParameterName = "p_path";
            s_lnk.DbType        = CustomDBType.VarChar;
            s_lnk.Direction     = ParameterDirection.Input;
            s_lnk.Size          = 255;
            s_lnk.Index         = 0;
            s_lnk.Value         = s_ModuleSrc;

            S_Controls.Collections.S_Object s_UserName = new S_Object();
            s_UserName.ParameterName = "p_UserName";
            s_UserName.DbType        = CustomDBType.VarChar;
            s_UserName.Direction     = ParameterDirection.Input;
            s_UserName.Size          = 50;
            s_UserName.Index         = 1;
            string s_User = string.Empty;

            if (context.User != null)
            {
                s_User = context.User.Identity.Name;
            }
            else
            {
                System.Web.Security.FormsAuthenticationTicket ticket = System.Web.Security.FormsAuthentication.Decrypt(context.Request.Cookies[FormsAuthentication.FormsCookieName].Value);

                s_User = ticket.Name;
            }
            s_UserName.Value = s_User;

            S_Controls.Collections.S_Object s_Cursor = new S_Object();
            s_Cursor.ParameterName = "IO_CURSOR";
            s_Cursor.DbType        = CustomDBType.Cursor;
            s_Cursor.Direction     = ParameterDirection.Output;
            s_Cursor.Index         = 2;

            _SCollection.Add(s_lnk);
            _SCollection.Add(s_UserName);
            _SCollection.Add(s_Cursor);

            ApplicationDataLayer.OracleDataLayer _OraDl = new OracleDataLayer(s_ConnStr);
            string s_StrSql = "SITO.SP_GETSETTINGS_PAGE";

            _Ds = _OraDl.GetRows(_SCollection, s_StrSql).Copy();

            if (_Ds.Tables[0].Rows.Count == 1)
            {
                this.s_ModuleTitle = _Ds.Tables[0].Rows[0]["DESCRIZIONE"].ToString();
                decimal i_Modifica = (decimal)_Ds.Tables[0].Rows[0]["ISMODIFICA"];
                this.i_ModuleId = int.Parse(_Ds.Tables[0].Rows[0]["FUNZIONE_ID"].ToString());

                if (i_Modifica < 0)
                {
                    this.b_IsEditable = true;
                }
                else
                {
                    this.b_IsEditable = false;
                }

                decimal i_Stampa = (decimal)_Ds.Tables[0].Rows[0]["ISSTAMPA"];
                if (i_Stampa < 0)
                {
                    this.b_IsPrintable = true;
                }
                else
                {
                    this.b_IsPrintable = false;
                }

                decimal i_Cancella = (decimal)_Ds.Tables[0].Rows[0]["ISCANCELLAZIONE"];
                if (i_Cancella < 0)
                {
                    this.b_IsDeletable = true;
                }
                else
                {
                    this.b_IsDeletable = false;
                }

                if (_Ds.Tables[0].Rows[0]["LINK"] != DBNull.Value)
                {
                    this.s_Link = _Ds.Tables[0].Rows[0]["LINK"].ToString();
                }
                if (_Ds.Tables[0].Rows[0]["LINK_HELP"] != DBNull.Value)
                {
                    this.s_HelpLink = System.Configuration.ConfigurationSettings.AppSettings["LinkHelp"] + _Ds.Tables[0].Rows[0]["LINK_HELP"].ToString();
                }

                //	this.s_HelpLink = _Ds.Tables[0].Rows[0]["LINK_HELP"].ToString();
            }
        }
Example #34
0
 private MemoryCacheProvider()//System.Web.HttpContext oContext
 {
     _oContext = HttpContext.Current;
 }
Example #35
0
        /// <summary>
        /// This is the core Function that writes to the HTTP Response Stream when Gateway contents are requested.
        /// No need to check strAction here as we will only get one type of request, "VWGDownload"
        /// </summary>
        /// <param name="objHttpContext"></param>
        /// <param name="strAction"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        protected override Gizmox.WebGUI.Common.Interfaces.IGatewayHandler ProcessGatewayRequest(System.Web.HttpContext objHttpContext, string strAction)
        {
            //Get HTTP Response Object
            HttpResponse objResponse = objHttpContext.Response;

            //Set the Content-Type
            if (this.myContentType != null)
            {
                objResponse.ContentType = myContentType;
            }

            //Set Filename Header
            if (this.myDownloadAsAttachment == true & this.myTargetFilename != null)
            {
                //add the response headers
                objResponse.AddHeader("content-disposition", "attachment; filename=\"" + this.myTargetFilename + "\"");
            }

            //Send File out to HTTP Stream
            if (myStream == null)
            {
                //Write to Stream using using FileStream
                objResponse.WriteFile(myFilePath);
            }
            else
            {
                //Write to Stream using Byte Array
                byte[] myByteArray = GetStreamAsByteArray(myStream);
                objResponse.BinaryWrite(myByteArray);
            }

            //Remove Myself from Container
            myContainer.Controls.Remove(this);

            return(null);
        }
Example #36
0
        protected void GetClientIPAddress()
        {
            try
            {
                System.Web.HttpContext context = System.Web.HttpContext.Current;

                string IP1 = HttpContext.Current.Request.UserHostAddress;
                string IP2 = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                //To get the IP address of the machine and not the proxy use the following code
                string IP3 = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (!string.IsNullOrEmpty(IP3))
                {
                    string[] addresses = IP3.Split(',');
                    if (addresses.Length != 0)
                    {
                    }
                }
                if (IP3 == null)
                {
                    IP3 = "";
                }


                string Browser   = "";
                string IsBrowser = "";
                IsBrowser = context.Request.Browser.IsMobileDevice.ToString();
                string Browser1 = Request.Browser.Browser + " " + Request.Browser.Version;
                if (IsBrowser == "True")
                {
                    Browser = "Mobile";
                }
                else
                {
                    Browser = "Web";
                }

                string BrowserDetail = "";
                if (context.Request.ServerVariables["HTTP_X_WAP_PROFILE"] != null)
                {
                    BrowserDetail = BrowserDetail + "|" + context.Request.ServerVariables["HTTP_X_WAP_PROFILE"];
                }

                if (context.Request.ServerVariables["HTTP_ACCEPT"] != null &&
                    context.Request.ServerVariables["HTTP_ACCEPT"].ToLower().Contains("wap"))
                {
                    BrowserDetail = BrowserDetail + "|" + context.Request.ServerVariables["HTTP_ACCEPT"];
                }

                if (context.Request.ServerVariables["HTTP_USER_AGENT"] != null)
                {
                    BrowserDetail = BrowserDetail + "|" + context.Request.ServerVariables["HTTP_USER_AGENT"];
                }

                //string ss = Request.Browser.ToString();
                //string ss2 = Request.Browser.Version.ToString();

                SLoginHistory sl = new SLoginHistory();

                sl.IpAddress1  = IP1;
                sl.IpAddress2  = IP2;
                sl.IpAddress3  = IP3;
                sl.BrowserName = Browser;
                sl.Browser1    = Browser1;
                sl.Location    = "Portal";
                sl.IpDetail    = BrowserDetail;
                sl.LoginID     = Convert.ToInt32(Session["LoginID"]);
                sl.LoginTime   = DateTime.Now;
                svc.InsertLoginHistoryService(sl);
            }
            catch (Exception ex)
            {
            }
            // return context.Request.ServerVariables["REMOTE_ADDR"];
        }
Example #37
0
 /// <summary>
 /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
 /// </summary>
 /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
 public void ProcessRequest(System.Web.HttpContext context)
 {
     context.Response.StatusCode = StatusCode;
     context.Response.End();
     return;
 }
Example #38
0
        public async Task <IEmailServerSearchViewModel> SearchAsync(System.Web.HttpContext httpContext, ISearchModel model, CancellationToken cancellationToken)
        {
            IEmailServerSearchViewModel tdModel = await SearchDataAsync(model, null, cancellationToken);

            return(tdModel);
        }
Example #39
0
        private void UploadImage(System.Web.HttpContext context, System.Web.HttpPostedFile file, string snailtype)
        {
            string str  = "/storage/data/grade";
            string text = System.Guid.NewGuid().ToString("N", System.Globalization.CultureInfo.InvariantCulture) + System.IO.Path.GetExtension(file.FileName);
            string str2 = str + "/images/" + text;

            if (this.uploadType.ToLower() == UploadType.SharpPic.ToString().ToLower())
            {
                str  = "/Storage/data/Sharp/";
                text = System.DateTime.Now.ToString("yyyyMMddHHmmss") + System.IO.Path.GetExtension(file.FileName);
                str2 = str + text;
            }
            else if (this.uploadType.ToLower() == UploadType.Vote.ToString().ToLower())
            {
                str  = "/Storage/master/vote/";
                str2 = str + text;
            }
            else if (this.uploadType.ToLower() == UploadType.Topic.ToString().ToLower())
            {
                str  = "/Storage/master/topic/";
                str2 = str + text;
            }
            else if (this.uploadType.ToLower() == UploadType.Weibo.ToString().ToLower())
            {
                str  = "/Storage/master/Weibo/";
                str2 = str + text;
            }
            if (this.uploadType.ToLower() == UploadType.Brand.ToString().ToLower())
            {
                str  = "/Storage/master/brand/";
                str2 = str + text;
            }
            else if (this.uploadType.ToLower() == UploadType.ShopMenu.ToString().ToLower())
            {
                str  = "/Storage/master/ShopMenu/";
                str2 = str + text;
                int num = 0;
                if (!string.IsNullOrEmpty(this.uploadSize))
                {
                    if (!int.TryParse(this.uploadSize, out num))
                    {
                        this.WriteBackError(context, "UploadSize属性值只能是数字!");
                        return;
                    }
                    if (file.ContentLength > num)
                    {
                        this.WriteBackError(context, "文件大小不超过10KB!");
                        return;
                    }
                }
                string text2 = System.IO.Path.GetExtension(file.FileName).ToLower();
                if (!text2.Equals(".gif") && !text2.Equals(".jpg") && !text2.Equals(".jpeg") && !text2.Equals(".png") && !text2.Equals(".bmp"))
                {
                    this.WriteBackError(context, "请上传正确的图片文件。");
                    return;
                }
            }
            string str3          = str + "/thumbs40/40_" + text;
            string str4          = str + "/thumbs60/60_" + text;
            string str5          = str + "/thumbs100/100_" + text;
            string str6          = str + "/thumbs160/160_" + text;
            string str7          = str + "/thumbs180/180_" + text;
            string str8          = str + "/thumbs220/220_" + text;
            string str9          = str + "/thumbs310/310_" + text;
            string str10         = str + "/thumbs410/410_" + text;
            string imageFilePath = context.Request.MapPath(Globals.ApplicationPath + str2);
            string a             = Globals.UploadFileAndCheck(file, imageFilePath);

            if (a == "1")
            {
                string sourceFilename = context.Request.MapPath(Globals.ApplicationPath + str2);
                if (snailtype == "1")
                {
                    ResourcesHelper.CreateThumbnail(sourceFilename, context.Request.MapPath(Globals.ApplicationPath + str3), 40, 40);
                    ResourcesHelper.CreateThumbnail(sourceFilename, context.Request.MapPath(Globals.ApplicationPath + str4), 60, 60);
                    ResourcesHelper.CreateThumbnail(sourceFilename, context.Request.MapPath(Globals.ApplicationPath + str5), 100, 100);
                    ResourcesHelper.CreateThumbnail(sourceFilename, context.Request.MapPath(Globals.ApplicationPath + str6), 160, 160);
                    ResourcesHelper.CreateThumbnail(sourceFilename, context.Request.MapPath(Globals.ApplicationPath + str7), 180, 180);
                    ResourcesHelper.CreateThumbnail(sourceFilename, context.Request.MapPath(Globals.ApplicationPath + str8), 220, 220);
                    ResourcesHelper.CreateThumbnail(sourceFilename, context.Request.MapPath(Globals.ApplicationPath + str9), 310, 310);
                    ResourcesHelper.CreateThumbnail(sourceFilename, context.Request.MapPath(Globals.ApplicationPath + str10), 410, 410);
                }
            }
            string[] value = new string[]
            {
                "'" + this.uploadType + "'",
                "'" + this.uploaderId + "'",
                "'" + str2 + "'",
                string.Concat(new string[]
                {
                    "'",
                    snailtype,
                    "','",
                    this.uploadSize,
                    "'"
                })
            };
            context.Response.Write("<script type=\"text/javascript\">window.parent.UploadCallback(" + string.Join(",", value) + ");</script>");
        }
Example #40
0
 public NativeNotify(System.Web.HttpContext page) : base(page)
 {
 }
 /// <summary>
 /// Creates a new <see cref="SessionStateStoreData"/> object for the current request.
 /// </summary>
 /// <param name="context">
 /// The HttpContext object for the current request.
 /// </param>
 /// <param name="timeout">
 /// The timeout value (in minutes) for the SessionStateStoreData object that is created.
 /// </param>
 public override SessionStateStoreData CreateNewStoreData(System.Web.HttpContext context, int timeout)
 {
     return(new SessionStateStoreData(new SessionStateItemCollection(),
                                      SessionStateUtility.GetSessionStaticObjects(context), timeout));
 }
 /// <summary>
 /// Allows the <see cref="MySqlSessionStateStore"/> object to perform any cleanup that may be
 /// required for the current request.
 /// </summary>
 /// <param name="context">The HttpContext object for the current request.</param>
 public override void EndRequest(System.Web.HttpContext context)
 {
 }
Example #43
0
 public void ProcessRequest(System.Web.HttpContext context)
 {
     context.Response.ContentType = "text/plain";
     context.Response.Write(this.ModelFolder(context));
 }
Example #44
0
        public void ProcessRequest(System.Web.HttpContext context)
        {
            string text = context.Request.Form["actionName"];
            string s    = string.Empty;
            string key;

            switch (key = text)
            {
            case "Topic":
            {
                System.Collections.Generic.IList <TopicInfo> value = VShopHelper.Gettopics();
                s = JsonConvert.SerializeObject(value);
                break;
            }

            case "Vote":
            {
                System.Data.DataSet votes = StoreHelper.GetVotes();
                s = JsonConvert.SerializeObject(votes);
                break;
            }

            case "Category":
            {
                var value2 =
                    from item in CatalogHelper.GetMainCategories()
                    select new
                {
                    CateId   = item.CategoryId,
                    CateName = item.Name
                };
                s = JsonConvert.SerializeObject(value2);
                break;
            }

            case "Activity":
            {
                System.Array values = System.Enum.GetValues(typeof(LotteryActivityType));
                System.Collections.Generic.List <VsiteHandler.EnumJson> list = new System.Collections.Generic.List <VsiteHandler.EnumJson>();
                foreach (System.Enum @enum in values)
                {
                    list.Add(new VsiteHandler.EnumJson
                        {
                            Name  = @enum.ToShowText(),
                            Value = @enum.ToString()
                        });
                }
                s = JsonConvert.SerializeObject(list);
                break;
            }

            case "ActivityList":
            {
                string value3 = context.Request.Form["acttype"];
                LotteryActivityType lotteryActivityType = (LotteryActivityType)System.Enum.Parse(typeof(LotteryActivityType), value3);
                if (lotteryActivityType == LotteryActivityType.SignUp)
                {
                    var value4 =
                        from item in VShopHelper.GetAllActivity()
                        select new
                    {
                        ActivityId   = item.ActivityId,
                        ActivityName = item.Name
                    };
                    s = JsonConvert.SerializeObject(value4);
                }
                else
                {
                    System.Collections.Generic.IList <LotteryActivityInfo> lotteryActivityByType = VShopHelper.GetLotteryActivityByType(lotteryActivityType);
                    s = JsonConvert.SerializeObject(lotteryActivityByType);
                }
                break;
            }

            case "ArticleCategory":
            {
                System.Collections.Generic.IList <ArticleCategoryInfo> articleMainCategories = CommentBrowser.GetArticleMainCategories();
                if (articleMainCategories != null && articleMainCategories.Count > 0)
                {
                    System.Collections.Generic.List <VsiteHandler.EnumJson> list2 = new System.Collections.Generic.List <VsiteHandler.EnumJson>();
                    foreach (ArticleCategoryInfo current in articleMainCategories)
                    {
                        list2.Add(new VsiteHandler.EnumJson
                            {
                                Name  = current.Name,
                                Value = current.CategoryId.ToString()
                            });
                    }
                    s = JsonConvert.SerializeObject(list2);
                }
                break;
            }

            case "ArticleList":
            {
                int categoryId = 0;
                if (context.Request.Form["categoryId"] != null)
                {
                    int.TryParse(context.Request.Form["categoryId"].ToString(), out categoryId);
                }
                System.Collections.Generic.IList <ArticleInfo>          articleList = CommentBrowser.GetArticleList(categoryId, 1000);
                System.Collections.Generic.List <VsiteHandler.EnumJson> list3       = new System.Collections.Generic.List <VsiteHandler.EnumJson>();
                foreach (ArticleInfo current2 in articleList)
                {
                    list3.Add(new VsiteHandler.EnumJson
                        {
                            Name  = current2.Title,
                            Value = current2.ArticleId.ToString()
                        });
                }
                s = JsonConvert.SerializeObject(list3);
                break;
            }
            }
            context.Response.Write(s);
        }
Example #45
0
 /// <summary>
 /// Gets the unique service name for the current operation.
 /// </summary>
 /// <param name="context">The current http context.</param>
 /// <returns>The unique service name</returns>
 public abstract string ServiceName(System.Web.HttpContext context);
Example #46
0
 /// <summary>
 /// Get the collection of virtual paths that are to be executed in sequence.
 /// </summary>
 /// <param name="context">The current http context.</param>
 /// <param name="serviceName">The unique service method name.</param>
 /// <returns>The collection of virtual paths.</returns>
 public abstract string[] VirtualPageUriCollection(System.Web.HttpContext context, string serviceName);
Example #47
0
 /// <summary>
 /// Construct object to manage XML repositories
 /// </summary>
 /// <param name="context">HttpContext</param>
 /// <remarks>
 /// Context is passed to provide access to request, response, server,
 /// cookie, etc., objects. Normally it's accessible as a static method
 /// but since the Xml class can be created by a spawned thread, the
 /// static member may be null, so pass context explicitly.
 /// </remarks>
 public Xml(System.Web.HttpContext context)
 {
     _context = context;
 }
Example #48
0
        /// <summary>
        /// Process request method.
        /// </summary>
        /// <param name="context">The current http context.</param>
        public void ProcessRequest(System.Web.HttpContext context)
        {
            MemoryStream receivedMessageData = null;
            MemoryStream sendMessageData     = null;
            string       serviceName         = string.Empty;

            try
            {
                // Initialise the composition assembly collection.
                Compose();

                // Get the current service name request.
                serviceName = ServiceName(context);

                // Get the collection of virtual pages to load.
                string[] virtualPages = VirtualPageUriCollection(context, serviceName);

                try
                {
                    // Execute each of the virtual pages, into
                    // one single response handler.
                    if (virtualPages != null)
                    {
                        foreach (string item in virtualPages)
                        {
                            context.Server.Execute(item);
                        }
                    }
                }
                catch (Exception exVirtualUri)
                {
                    // Get the current exception.
                    Exception = exVirtualUri;
                }
            }
            catch (System.Threading.ThreadAbortException)
            { }
            catch (Exception ex)
            {
                // Get the current exception.
                Exception = ex;
            }
            finally
            {
                // Clean-up
                if (receivedMessageData != null)
                {
                    receivedMessageData.Close();
                }

                // Clean-up
                if (sendMessageData != null)
                {
                    sendMessageData.Close();
                }

                // Clean-up
                if (context.Response != null)
                {
                    if (context.Response.OutputStream != null)
                    {
                        context.Response.OutputStream.Close();
                    }
                }

                // Clean-up
                if (context.Request != null)
                {
                    if (context.Request.InputStream != null)
                    {
                        context.Request.InputStream.Close();
                    }
                }
            }
        }
        public static string DoImport(PortalSettings objPortalSettings, string LocalResourceFile, UserInfo currentUserInfo)
        {
            System.Web.HttpContext objContext = System.Web.HttpContext.Current;

            if (objContext.Request.Files.Count == 0)
            {
                return(Localization.GetString("ImportFileMissed", LocalResourceFile));
            }

            bool UpdateExistingUser = Convert.ToBoolean(objContext.Request.Form["cbUpdateExistingUser"]);

            HttpPostedFile objFile = objContext.Request.Files[0];

            System.IO.FileInfo objFileInfo = new System.IO.FileInfo(objFile.FileName);
            byte[]             lstBytes    = new byte[(int)objFile.InputStream.Length];
            objFile.InputStream.Read(lstBytes, 0, (int)objFile.InputStream.Length);

            DataTable dt = null;

            switch (objFileInfo.Extension.ToLower())
            {
            case ".csv":
            case ".txt":
                dt = CSV2Table(lstBytes);
                break;

            case ".xml":
                dt = XML2Table(lstBytes);
                break;
            }

            ProfilePropertyDefinition objOldUserID = DotNetNuke.Entities.Profile.ProfileController.GetPropertyDefinitionByName(objPortalSettings.PortalId, "OldUserID");

            if (objOldUserID == null)
            {
                objOldUserID = new ProfilePropertyDefinition(objPortalSettings.PortalId);
                objOldUserID.PropertyName     = "OldUserID";
                objOldUserID.PropertyCategory = "Imported";
                objOldUserID.DataType         = 349;
                DotNetNuke.Entities.Profile.ProfileController.AddPropertyDefinition(objOldUserID);
            }

            string NonProfileFields = ",userid,username,firstname,lastname,displayname,issuperuser,email,affiliateid,authorised,isdeleted,roleids,roles,";

            string SubjectTemplate = Localization.GetString("EmailUserSubject", LocalResourceFile);
            string BodyTemplate    = Localization.GetString("EmailUserBody", LocalResourceFile);

            int           UsersCount        = 0;
            int           SuccessUsersCount = 0;
            StringBuilder FailedUsers       = new StringBuilder();

            foreach (DataRow dr in dt.Rows)
            {
                UsersCount++;
                try
                {
                    DotNetNuke.Entities.Users.UserInfo objUser = new DotNetNuke.Entities.Users.UserInfo();
                    //use email as username, when username is not provided
                    objUser.Username = string.Format("{0}", GetDataRowValue(dt, dr, "Username", objUser.Email));

                    bool UserAlreadyExists = false;
                    if (UpdateExistingUser)
                    {
                        objUser = UserController.GetUserByName(objPortalSettings.PortalId, objUser.Username);
                        if (objUser != null)
                        {
                            UserAlreadyExists = true;
                        }
                    }


                    objUser.Profile.InitialiseProfile(objPortalSettings.PortalId, true);
                    objUser.Email       = string.Format("{0}", dr["Email"]);
                    objUser.FirstName   = string.Format("{0}", dr["FirstName"]);
                    objUser.LastName    = string.Format("{0}", dr["LastName"]);
                    objUser.DisplayName = string.Format("{0}", GetDataRowValue(dt, dr, "DisplayName", string.Format("{0} {1}", dr["FirstName"], dr["LastName"])));
                    objUser.PortalID    = objPortalSettings.PortalId;

                    objUser.IsSuperUser = ObjectToBool(GetDataRowValue(dt, dr, "IsSuperUser", "0"));

                    //only SuperUsers allowed to import users with SuperUsers rights
                    if ((!currentUserInfo.IsSuperUser) && objUser.IsSuperUser)
                    {
                        FailedUsers.AppendFormat(
                            string.Format(Localization.GetString("Line", LocalResourceFile), UsersCount) +
                            Localization.GetString("UserDeniedToImportRole", LocalResourceFile),
                            currentUserInfo.Username,
                            "SuperUser");
                        continue;
                    }

                    if (dt.Columns.Contains("Password"))
                    {
                        objUser.Membership.Password = string.Format("{0}", dr["Password"]);
                    }
                    objUser.Membership.Password = ValidatePassword(objUser, Convert.ToBoolean(objContext.Request.Form["cbRandomPassword"]));

                    int AffiliateID = -1;
                    if (Int32.TryParse(string.Format("{0}", GetDataRowValue(dt, dr, "AffiliateId", -1)), out AffiliateID))
                    {
                        objUser.AffiliateID = AffiliateID;
                    }

                    objUser.Membership.Approved         = true;
                    objUser.Membership.PasswordQuestion = objUser.Membership.Password;
                    objUser.Membership.UpdatePassword   = Convert.ToBoolean(objContext.Request.Form["cbForcePasswordChange"]);                  //update password on next login

                    DotNetNuke.Security.Membership.UserCreateStatus objCreateStatus;
                    if (UserAlreadyExists)
                    {
                        objCreateStatus = DotNetNuke.Security.Membership.UserCreateStatus.Success;
                    }
                    else
                    {
                        objCreateStatus = UserController.CreateUser(ref objUser);
                    }

                    if (objCreateStatus == DotNetNuke.Security.Membership.UserCreateStatus.Success)
                    {
                        if (dt.Columns.IndexOf("UserID") != -1)
                        {
                            objUser.Profile.SetProfileProperty("OldUserID", string.Format("{0}", dr["UserID"]));
                        }
                        SuccessUsersCount++;

                        //Update Profile
                        objUser.Profile.Country    = string.Format("{0}", GetDataRowValue(dt, dr, "Country", ""));
                        objUser.Profile.Street     = string.Format("{0}", GetDataRowValue(dt, dr, "Street", ""));
                        objUser.Profile.City       = string.Format("{0}", GetDataRowValue(dt, dr, "City", ""));
                        objUser.Profile.Region     = string.Format("{0}", GetDataRowValue(dt, dr, "Region", ""));
                        objUser.Profile.PostalCode = string.Format("{0}", GetDataRowValue(dt, dr, "PostalCode", ""));
                        objUser.Profile.Unit       = string.Format("{0}", GetDataRowValue(dt, dr, "Unit", ""));
                        objUser.Profile.Telephone  = string.Format("{0}", GetDataRowValue(dt, dr, "Telephone", ""));
                        objUser.Profile.FirstName  = objUser.FirstName;
                        objUser.Profile.LastName   = objUser.LastName;

                        //Profile Properties
                        if (Convert.ToBoolean(objContext.Request.Form["cbImportProfileProperties"]))
                        {
                            foreach (DataColumn dc in dt.Columns)
                            {
                                if (NonProfileFields.IndexOf(string.Format(",{0},", dc.ColumnName.ToLower())) != -1)
                                {
                                    continue;
                                }
                                //check if profile property exists
                                ProfilePropertyDefinition objPPD = DotNetNuke.Entities.Profile.ProfileController.GetPropertyDefinitionByName(objPortalSettings.PortalId, dc.ColumnName);
                                if ((objPPD == null) && (Convert.ToBoolean(objContext.Request.Form["cbCreateMissedProfileProperties"])))
                                {
                                    objPPD = new ProfilePropertyDefinition(objPortalSettings.PortalId);
                                    objPPD.PropertyName     = dc.ColumnName;
                                    objPPD.PropertyCategory = "Imported";
                                    objPPD.DataType         = 349;
                                    DotNetNuke.Entities.Profile.ProfileController.AddPropertyDefinition(objPPD);
                                    objUser.Profile.SetProfileProperty(dc.ColumnName, string.Format("{0}", dr[dc.ColumnName]));
                                }
                                else
                                {
                                    objUser.Profile.SetProfileProperty(dc.ColumnName, string.Format("{0}", dr[dc.ColumnName]));
                                }
                            }
                        }
                        ProfileController.UpdateUserProfile(objUser);
                        UserController.UpdateUser(objPortalSettings.PortalId, objUser);

                        //Update Roles
                        string RolesStatus = UpdateRoles(currentUserInfo, objPortalSettings, objUser, dr, objContext.Request.Form["rblImportRoles"], LocalResourceFile);
                        if (RolesStatus.Trim() != "")
                        {
                            FailedUsers.AppendFormat(Localization.GetString("UpdateRolesError", LocalResourceFile),
                                                     UsersCount,
                                                     objUser.UserID,
                                                     RolesStatus);
                        }

                        if (Convert.ToBoolean(objContext.Request.Form["cbEmailUser"]))
                        {
                            string SendEmailResult = CommonController.SendEmail(objUser, SubjectTemplate, BodyTemplate, objPortalSettings);

                            switch (SendEmailResult)
                            {
                            case "":
                                //success
                                break;

                            case "InvalidEmail":
                                FailedUsers.AppendFormat(Localization.GetString("SendEmailInvalidEmailException", LocalResourceFile),
                                                         UsersCount,
                                                         objUser.Username,
                                                         objUser.Email);
                                break;

                            default:
                                FailedUsers.AppendFormat(Localization.GetString("SendEmailException", LocalResourceFile),
                                                         UsersCount,
                                                         objUser.Username,
                                                         SendEmailResult);
                                break;
                            }
                        }
                    }
                    else
                    {
                        FailedUsers.AppendFormat(Localization.GetString("RowMembershipError", LocalResourceFile),
                                                 UsersCount,
                                                 objUser.Username,
                                                 objCreateStatus.ToString());
                    }
                }
                catch (Exception Exc)
                {
                    FailedUsers.AppendFormat(Localization.GetString("RowException", LocalResourceFile),
                                             UsersCount,
                                             Exc.Message);
                    Exceptions.LogException(Exc);
                }
            }
            return(string.Format(Localization.GetString("Result", LocalResourceFile),
                                 UsersCount,
                                 SuccessUsersCount,
                                 FailedUsers.ToString()));
        }
Example #50
0
        public void ProcessRequest(System.Web.HttpContext context)
        {
            try
            {
                SiteSettings masterSettings = SettingsManager.GetMasterSettings(true);
                string       s      = "";
                string       text   = context.Request["action"];
                int          menuId = 0;
                int.TryParse(context.Request["menuId"], out menuId);
                string roleId  = context.Request["roleId"];
                string menuIds = context.Request["menuIds"];
                if (false & text != "checklogin") // &&
                {
                    if (text == "all")
                    {
                        string cur = System.Web.HttpContext.Current.Request["Supplier"];
                        if (!string.IsNullOrWhiteSpace(cur))
                        {
                            s = "{\"status\":\"1,1,1,1,1\",\"Supplier\":\"true\"}";
                        }
                        else
                        {
                            s = "{\"status\":\"1,1,1,1,1\"}";
                        }
                    }
                    else
                    {
                        s = "{\"status\":\"1\"}";
                    }
                }
                else
                {
                    string key;
                    switch (key = text)
                    {
                    case "vstore":
                        s = "{\"status\":\"" + masterSettings.OpenVstore + "\"}";
                        break;

                    case "wapshop":
                        s = "{\"status\":\"" + masterSettings.OpenWap + "\"}";
                        break;

                    case "appshop":
                        s = "{\"status\":\"" + masterSettings.OpenMobbile + "\"}";
                        break;

                    case "alioh":
                        s = "{\"status\":\"" + masterSettings.OpenAliho + "\"}";
                        break;

                    case "taobao":
                        s = "{\"status\":\"" + masterSettings.OpenTaobao + "\"}";
                        break;

                    case "GetFirstMenu":
                        s = this.GetFisrtMenuInfo();
                        break;

                    case "GetMenuById":
                        s = this.GetMenuInfoByFirstId(menuId);
                        break;

                    case "GetAllMenuByRoleId":
                        s = this.GetAllMenuInfoByRoleId(roleId);
                        break;

                    case "all":
                        s = string.Concat(new object[]
                        {
                            "{\"status\":\"",
                            masterSettings.OpenTaobao,
                            ",",
                            masterSettings.OpenVstore,
                            ",",
                            masterSettings.OpenMobbile,
                            ",",
                            masterSettings.OpenWap,
                            ",",
                            masterSettings.OpenAliho,
                            "\"}"
                        });
                        break;

                    case "checklogin":
                        s = this.ChkLogin();
                        break;
                    }
                }
                context.Response.ContentType = "application/json";
                context.Response.Write(s);
            }
            catch (System.Exception ex)
            {
                context.Response.ContentType = "application/json";
                context.Response.Write("{\"status\":\"" + ex.Message + "\"}");
            }
        }
Example #51
0
        public void ProcessRequest(System.Web.HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            if (Globals.GetCurrentManagerUserId() <= 0)
            {
                context.Response.Write("请先登录");
                context.Response.End();
            }
            string text = Globals.RequestFormStr("action");

            if (!string.IsNullOrEmpty(text))
            {
                if (text == "End")
                {
                    int num = Globals.RequestFormNum("delId");
                    if (num > 0)
                    {
                        if (ActivityHelper.EndAct(num))
                        {
                            context.Response.Write("{\"state\":\"true\",\"msg\":\"活动成功结束\"}");
                            return;
                        }
                        context.Response.Write("{\"state\":\"false\",\"msg\":\"活动结束失败\"}");
                        return;
                    }
                    else
                    {
                        context.Response.Write("{\"state\":\"false\",\"msg\":\"参数不正确\"}");
                    }
                }
                return;
            }
            try
            {
                int             num2       = int.Parse(context.Request["id"].ToString());
                string          text2      = context.Request["name"].ToString();
                string          val        = context.Request["begin"].ToString();
                string          val2       = context.Request["end"].ToString();
                string          text3      = context.Request["memberlvl"].ToString();
                string          text4      = context.Request["defualtGroup"].ToString();
                string          text5      = context.Request["customGroup"].ToString();
                string          val3       = context.Request["maxNum"].ToString();
                string          val4       = context.Request["type"].ToString();
                string          val5       = context.Request["attendType"].ToString();
                string          val6       = context.Request["meetType"].ToString();
                int             attendType = 0;
                int             meetType   = 0;
                System.DateTime now        = System.DateTime.Now;
                System.DateTime now2       = System.DateTime.Now;
                int             attendTime = 0;
                int             num3       = 0;
                if (text2.Length > 30)
                {
                    context.Response.Write("{\"type\":\"error\",\"data\":\"活动名称不能超过30个字符\"}");
                }
                else if (!val.bDate(ref now))
                {
                    context.Response.Write("{\"type\":\"error\",\"data\":\"请输入正确的开始时间\"}");
                }
                else if (!val2.bDate(ref now2))
                {
                    context.Response.Write("{\"type\":\"error\",\"data\":\"请输入正确的结束时间\"}");
                }
                else if (now2 < now)
                {
                    context.Response.Write("{\"type\":\"error\",\"data\":\"结束时间不能早于开始时间\"}");
                }
                else if (string.IsNullOrEmpty(text3) && string.IsNullOrEmpty(text4) && string.IsNullOrEmpty(text5))
                {
                    context.Response.Write("{\"type\":\"error\",\"data\":\"请选择适用会员等级\"}");
                }
                else if (!val3.bInt(ref attendTime))
                {
                    context.Response.Write("{\"type\":\"error\",\"data\":\"请选择参与次数\"}");
                }
                else if (!val4.bInt(ref num3))
                {
                    context.Response.Write("{\"type\":\"error\",\"data\":\"请选择参与商品类型\"}");
                }
                else if (!val5.bInt(ref attendType))
                {
                    context.Response.Write("{\"type\":\"error\",\"data\":\"请选择优惠类型\"}");
                }
                else if (!val6.bInt(ref meetType))
                {
                    context.Response.Write("{\"type\":\"error\",\"data\":\"请选择优惠条件\"}");
                }
                else
                {
                    System.Collections.Generic.List <ActivityDetailInfo> list = new System.Collections.Generic.List <ActivityDetailInfo>();
                    JArray jArray = (JArray)JsonConvert.DeserializeObject(context.Request.Form["stk"].ToString());
                    if (jArray.Count > 1)
                    {
                        for (int i = 0; i < jArray.Count - 1; i++)
                        {
                            JToken jToken = jArray[i]["meet"];
                            for (int j = i + 1; j < jArray.Count; j++)
                            {
                                if (jArray[j]["meet"] == jToken)
                                {
                                    context.Response.Write("{\"type\":\"error\",\"data\":\"多级优惠的各级满足金额不能相同\"}");
                                    return;
                                }
                            }
                        }
                    }
                    if (jArray.Count > 0)
                    {
                        for (int k = 0; k < jArray.Count; k++)
                        {
                            ActivityDetailInfo activityDetailInfo = new ActivityDetailInfo();
                            string             val7  = jArray[k]["meet"].ToString();
                            string             val8  = jArray[k]["meetNumber"].ToString();
                            string             val9  = jArray[k]["redus"].ToString();
                            string             val10 = jArray[k]["free"].ToString();
                            string             val11 = jArray[k]["point"].ToString();
                            string             val12 = jArray[k]["coupon"].ToString();
                            decimal            num4  = 0m;
                            int     num5             = 0;
                            decimal num6             = 0m;
                            int     integral         = 0;
                            int     couponId         = 0;
                            int     num7             = 0;
                            if (!val8.bInt(ref num5))
                            {
                                context.Response.Write("{\"type\":\"error\",\"data\":\"第" + (k + 1).ToString() + "级优惠满足次数输入错误!\"}");
                                return;
                            }
                            if (!val7.bDecimal(ref num4))
                            {
                                context.Response.Write("{\"type\":\"error\",\"data\":\"第" + (k + 1).ToString() + "级优惠满足金额输入错误!\"}");
                                return;
                            }
                            if (!val9.bDecimal(ref num6))
                            {
                                context.Response.Write("{\"type\":\"error\",\"data\":\"第" + (k + 1).ToString() + "级优惠减免金额输入错误!\"}");
                                return;
                            }
                            if (!val10.bInt(ref num7))
                            {
                                context.Response.Write("{\"type\":\"error\",\"data\":\"第" + (k + 1).ToString() + "级优惠免邮选择错误!\"}");
                                return;
                            }
                            bool bFreeShipping = num7 != 0;
                            if (!val11.bInt(ref integral))
                            {
                                context.Response.Write("{\"type\":\"error\",\"data\":\"第" + (k + 1).ToString() + "级优惠积分输入错误!\"}");
                                return;
                            }
                            if (!val11.bInt(ref integral))
                            {
                                context.Response.Write("{\"type\":\"error\",\"data\":\"第" + (k + 1).ToString() + "级优惠积分输入错误!\"}");
                                return;
                            }
                            if (!val12.bInt(ref couponId))
                            {
                                context.Response.Write("{\"type\":\"error\",\"data\":\"第" + (k + 1).ToString() + "级优惠优惠券选择错误!\"}");
                                return;
                            }
                            if (num5 == 0 && num6 > num4)
                            {
                                context.Response.Write("{\"type\":\"error\",\"data\":\"第" + (k + 1).ToString() + "级优惠减免金额不能大于满足金额!\"}");
                                return;
                            }
                            activityDetailInfo.ActivitiesId   = 0;
                            activityDetailInfo.bFreeShipping  = bFreeShipping;
                            activityDetailInfo.CouponId       = couponId;
                            activityDetailInfo.MeetMoney      = num4;
                            activityDetailInfo.MeetNumber     = num5;
                            activityDetailInfo.ReductionMoney = num6;
                            activityDetailInfo.Integral       = integral;
                            list.Add(activityDetailInfo);
                        }
                    }
                    ActivityInfo activityInfo = new ActivityInfo();
                    if (num2 != 0)
                    {
                        activityInfo = ActivityHelper.GetAct(num2);
                        if (activityInfo == null)
                        {
                            context.Response.Write("{\"type\":\"error\",\"data\":\"没有找到这个活动\"}");
                            return;
                        }
                    }
                    activityInfo.ActivitiesName = text2;
                    activityInfo.EndTime        = now2.Date.AddDays(1.0).AddSeconds(-1.0);
                    activityInfo.StartTime      = now.Date;
                    activityInfo.attendTime     = attendTime;
                    activityInfo.attendType     = attendType;
                    activityInfo.isAllProduct   = (num3 == 0);
                    activityInfo.MemberGrades   = text3;
                    activityInfo.DefualtGroup   = text4;
                    activityInfo.CustomGroup    = text5;
                    activityInfo.Type           = new int?(0);
                    activityInfo.MeetMoney      = 0m;
                    activityInfo.ReductionMoney = 0m;
                    activityInfo.Details        = list;
                    activityInfo.MeetType       = meetType;
                    string str = "";
                    int    num8;
                    if (num2 == 0)
                    {
                        num8 = ActivityHelper.Create(activityInfo, ref str);
                    }
                    else
                    {
                        num8 = activityInfo.ActivitiesId;
                        if (!ActivityHelper.Update(activityInfo, ref str))
                        {
                            num8 = 0;
                        }
                    }
                    if (num8 > 0)
                    {
                        context.Response.Write("{\"type\":\"success\",\"data\":\"" + num8.ToString() + "\"}");
                    }
                    else
                    {
                        context.Response.Write("{\"type\":\"error\",\"data\":\"" + str + "\"}");
                    }
                }
            }
            catch (System.Exception ex)
            {
                context.Response.Write("{\"type\":\"error\",\"data\":\"" + ex.Message + "\"}");
            }
        }
Example #52
0
        public void ProcessRequest(System.Web.HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            if (Globals.GetCurrentManagerUserId() <= 0)
            {
                context.Response.Write("{\"type\":\"error\",\"data\":\"请先登录\"}");
                context.Response.End();
            }
            int num = 0;

            int.TryParse(context.Request["id"].ToString(), out num);
            CustomerServiceSettings masterSettings = CustomerServiceManager.GetMasterSettings(false);
            string unit       = masterSettings.unit;
            string text       = context.Request["userver"].ToString();
            string password   = context.Request["password"].ToString();
            string text2      = context.Request["nickname"].ToString();
            string value      = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5");
            string tokenValue = TokenApi.GetTokenValue(masterSettings.AppId, masterSettings.AppSecret);

            if (string.IsNullOrEmpty(tokenValue))
            {
                context.Response.Write("{\"type\":\"error\",\"data\":\"获取access_token失败!\"}");
                return;
            }
            System.Collections.Generic.Dictionary <string, string> dictionary = new System.Collections.Generic.Dictionary <string, string>();
            dictionary.Add("unit", unit);
            dictionary.Add("userver", text);
            dictionary.Add("password", value);
            dictionary.Add("nickname", text2);
            dictionary.Add("realname", "");
            dictionary.Add("level", "");
            dictionary.Add("tel", "");
            string empty = string.Empty;
            CustomerServiceInfo customerServiceInfo = new CustomerServiceInfo();

            if (num != 0)
            {
                string text3 = CustomerApi.UpdateCustomer(tokenValue, dictionary);
                if (string.IsNullOrWhiteSpace(text3))
                {
                    context.Response.Write("{\"type\":\"error\",\"data\":\"修改客服信息失败!\"}");
                    return;
                }
                string jsonValue  = Hishop.MeiQia.Api.Util.Common.GetJsonValue(text3, "errcode");
                string jsonValue2 = Hishop.MeiQia.Api.Util.Common.GetJsonValue(text3, "errmsg");
                if (!(jsonValue == "0"))
                {
                    context.Response.Write("{\"type\":\"error\",\"data\":\"" + jsonValue2 + "\"}");
                    return;
                }
                customerServiceInfo          = CustomerServiceHelper.GetCustomer(num);
                customerServiceInfo.unit     = unit;
                customerServiceInfo.userver  = text;
                customerServiceInfo.password = password;
                customerServiceInfo.nickname = text2;
                bool flag = CustomerServiceHelper.UpdateCustomer(customerServiceInfo, ref empty);
                if (flag)
                {
                    context.Response.Write("{\"type\":\"success\",\"data\":\"\"}");
                    return;
                }
                context.Response.Write("{\"type\":\"error\",\"data\":\"" + empty + "\"}");
                return;
            }
            else
            {
                string text4 = CustomerApi.CreateCustomer(tokenValue, dictionary);
                if (string.IsNullOrWhiteSpace(text4))
                {
                    context.Response.Write("{\"type\":\"error\",\"data\":\"注册客服用户失败!\"}");
                    return;
                }
                string jsonValue3 = Hishop.MeiQia.Api.Util.Common.GetJsonValue(text4, "errcode");
                string jsonValue4 = Hishop.MeiQia.Api.Util.Common.GetJsonValue(text4, "errmsg");
                if (!(jsonValue3 == "0"))
                {
                    context.Response.Write("{\"type\":\"error\",\"data\":\"" + jsonValue4 + "\"}");
                    return;
                }
                customerServiceInfo.unit     = unit;
                customerServiceInfo.userver  = text;
                customerServiceInfo.password = password;
                customerServiceInfo.nickname = text2;
                int num2 = CustomerServiceHelper.CreateCustomer(customerServiceInfo, ref empty);
                if (num2 > 0)
                {
                    context.Response.Write("{\"type\":\"success\",\"data\":\"\"}");
                    return;
                }
                context.Response.Write("{\"type\":\"error\",\"data\":\"" + empty + "\"}");
                return;
            }
        }
Example #53
0
        } // End Function rand

        public void ProcessRequest(System.Web.HttpContext context)
        {
            string html = @"<!DOCTYPE html>
<html xmlns=""http://www.w3.org/1999/xhtml"" lang=""en"">
<head>
    <meta http-equiv=""X-UA-Compatible"" content=""IE=edge,chrome=1"" />

    <meta http-equiv=""cache-control"" content=""max-age=0"" />
    <meta http-equiv=""cache-control"" content=""no-cache"" />
    <meta http-equiv=""expires"" content=""0"" />
    <meta http-equiv=""expires"" content=""Tue, 01 Jan 1980 1:00:00 GMT"" />
    <meta http-equiv=""pragma"" content=""no-cache"" />

    <meta charset=""utf-8"" />
    <meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8"" />

    <meta http-equiv=""Content-Language"" content=""en"" />
    <meta name=""viewport"" content=""width=device-width,initial-scale=1"" />


    <!--
    <meta name=""author"" content=""name"" />
    <meta name=""description"" content=""description here"" />
    <meta name=""keywords"" content=""keywords,here"" />

    <link rel=""shortcut icon"" href=""favicon.ico"" type=""image/vnd.microsoft.icon"" />
    <link rel=""stylesheet"" href=""stylesheet.css"" type=""text/css"" />
    -->

    <title>Title</title>
    <style type=""text/css"" media=""all"">
        body
        {
            background-color: #0c70b4;
            color: #546775;
            font: normal 400 18px ""PT Sans"", sans-serif;
            -webkit-font-smoothing: antialiased;
        }

        .Table 
        {
            display: -webkit-box;
            display: -moz-box;
            display: box;
            display: -webkit-flex;
            display: -moz-flex;
            display: -ms-flexbox;
            display: flex;
            -webkit-flex-flow: column nowrap;
            -moz-flex-flow: column nowrap;
            flex-flow: column nowrap;
            -webkit-box-pack: justify;
            -moz-box-pack: justify;
            box-pack: justify;
            -webkit-justify-content: space-between;
            -moz-justify-content: space-between;
            -ms-justify-content: space-between;
            -o-justify-content: space-between;
            justify-content: space-between;
            -ms-flex-pack: justify;
            border: 1px solid #f2f2f2;
            font-size: 1rem;
            margin: 0.5rem;
            line-height: 1.5;
        }

        .Table-header 
        {
            display: none;
        }


        @media (min-width: 500px) 
        {

            .Table-header 
            {
            font-weight: 700;
            background-color: #f2f2f2;
            }

        }


        .Table-row 
        {
            width: 100%;
        }

        .Table-row:nth-of-type(even) 
        {
            background-color: #f2f2f2;
        }

        .Table-row:nth-of-type(odd) 
        {
            background-color: #ffffff;
        }


        @media (min-width: 500px) 
        {

            .Table-row 
            {
                display: -webkit-box;
                display: -moz-box;
                display: box;
                display: -webkit-flex;
                display: -moz-flex;
                display: -ms-flexbox;
                display: flex;
                -webkit-flex-flow: row nowrap;
                -moz-flex-flow: row nowrap;
                flex-flow: row nowrap;
            }

            .Table-row:nth-of-type(even) 
            {
                background-color: #ffffff;
            }

            .Table-row:nth-of-type(odd) 
            {
                background-color: #f2f2f2;
            }
        }


        .Table-row-item 
        {
            display: -webkit-box;
            display: -moz-box;
            display: box;
            display: -webkit-flex;
            display: -moz-flex;
            display: -ms-flexbox;
            display: flex;
            -webkit-flex-flow: row nowrap;
            -moz-flex-flow: row nowrap;
            flex-flow: row nowrap;
            -webkit-flex-grow: 1;
            -moz-flex-grow: 1;
            flex-grow: 1;
            -ms-flex-positive: 1;
            -webkit-flex-basis: 0;
            -moz-flex-basis: 0;
            flex-basis: 0;
            -ms-flex-preferred-size: 0;
            word-wrap: break-word;
            overflow-wrap: break-word;
            word-break: break-all;
            padding: 0.5em;
            word-break: break-word;
        }

        .Table-row-item:before 
        {
            content: attr(data-header);
            width: 30%;
            font-weight: 700;
        }


        @media (min-width: 500px) 
        {

            .Table-row-item 
            {
            border: 1px solid #ffffff;
            padding: 0.5em;
            }

            .Table-row-item:before 
            {
            content: none;
            }

        }

    </style>
</head>
<body>
    {@HTML}
</body>
</html>
";

            GetTableData(delegate(System.Data.Common.DbDataReader dr)
            {
                string table = responsiveTable("foo", dr);
                html         = html.Replace("{@HTML}", table);
            });

            context.Response.ContentType = "text/html";
            context.Response.Write(html);
        } // End Sub ProcessRequest
Example #54
0
        //grab the entire raw response
        //this may not be the best way to do this but the response is puuled in two formats:
        //ASCII and binary. We use the ascii copy to search the headers and chunks. Some utf-8
        //text may get mangled but atleast the character count is preserved. If we converted to
        //UTF-8, the text would look good but some multi-byte characters would distort the character
        //count. We use the binary data to parse out the needed chunks and then convert that to
        //UTF-8 which gets passed back to the client.
        private void GetResponse(System.Web.HttpContext context, string strReq)
        {
            NetworkStream ns = client.GetStream();

            Stream stream = null;

            if (useSsl)
            {
                var sslStream = new SslStream(ns);
                sslStream.AuthenticateAsClient(host);
                stream = sslStream;
            }
            else
            {
                stream = new BufferedStream(ns);
            }

            CustomTracer.Write("HttpSimpleSocket GetBody: got a response", context);

            ArrayList     lst     = new ArrayList();
            StringBuilder strBuff = new StringBuilder();

            try
            {
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strReq);
                stream.Write(bytes, 0, bytes.Length);

                buff = new byte[1024];
                int bytesRead = 0;

                try
                {
                    while ((bytesRead = stream.Read(buff, 0, buff.Length)) > 0)
                    {
                        byte[] cpy = new byte[bytesRead];
                        Array.Copy(buff, cpy, bytesRead);

                        lst.AddRange(cpy);
                        strBuff.Append(Encoding.ASCII.GetString(buff, 0, bytesRead));
                    }
                }
                catch (System.IO.IOException ioe)
                {
                    Exception inner = ioe.InnerException;
                    if (inner != null && inner is SocketException)
                    {
                        throw ioe.InnerException;
                    }
                    else
                    {
                        throw ioe;
                    }
                }

                buff = (byte[])lst.ToArray(Type.GetType("System.Byte"));
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
                client.Close();
            }

            body = strBuff.ToString();
        }
Example #55
0
        public void GetTopMenus(System.Web.HttpContext context)
        {
            context.Response.ContentType = "application/json";
            string text = "{";

            System.Collections.Generic.IList <MenuInfo> topFuwuMenus = VShopHelper.GetTopFuwuMenus();
            if (topFuwuMenus.Count <= 0)
            {
                text += "\"status\":\"-1\"";
                return;
            }
            object obj = text;

            text = string.Concat(new object[]
            {
                obj,
                "\"status\":\"0\",\"shopmenustyle\":\"0\",\"enableshopmenu\":\"",
                true,
                "\",\"data\":["
            });
            foreach (MenuInfo current in topFuwuMenus)
            {
                System.Collections.Generic.IList <MenuInfo> fuwuMenusByParentId = VShopHelper.GetFuwuMenusByParentId(current.MenuId);
                object obj2 = text;
                text = string.Concat(new object[]
                {
                    obj2,
                    "{\"menuid\": \"",
                    current.MenuId,
                    "\","
                });
                text += "\"childdata\":[";
                if (fuwuMenusByParentId.Count > 0)
                {
                    foreach (MenuInfo current2 in fuwuMenusByParentId)
                    {
                        object obj3 = text;
                        text = string.Concat(new object[]
                        {
                            obj3,
                            "{\"menuid\": \"",
                            current2.MenuId,
                            "\","
                        });
                        object obj4 = text;
                        text = string.Concat(new object[]
                        {
                            obj4,
                            "\"parentmenuid\": \"",
                            current2.ParentMenuId,
                            "\","
                        });
                        text = text + "\"type\": \"" + current2.Type + "\",";
                        text = text + "\"name\": \"" + current2.Name + "\",";
                        text = text + "\"content\": \"" + current2.Content + "\"},";
                    }
                    text = text.Substring(0, text.Length - 1);
                }
                text += "],";
                text  = text + "\"type\": \"" + current.Type + "\",";
                text  = text + "\"name\": \"" + current.Name + "\",";
                text += "\"shopmenupic\": \"\",";
                text  = text + "\"content\": \"" + current.Content + "\"},";
            }
            text  = text.Substring(0, text.Length - 1);
            text += "]";
            text += "}";
            context.Response.Write(text);
        }
Example #56
0
 public JsApiPay(System.Web.HttpContext page)
 {
     this.page = page;
 }
Example #57
0
        public Tuple <string, string, string> Login(LoginCommon common)
        {
            try
            {
                System.Web.HttpContext httpCtx = System.Web.HttpContext.Current;

                var    browserDetails = httpCtx.Request.Headers["User-Agent"];
                string Ipaddress      = ApplicationUtilities.GetIP();
                var    dbres          = _login.Login(new LoginCommon {
                    UserName = common.UserName, Password = common.Password, IpAddress = Ipaddress, BrowserDetail = browserDetails
                });

                if (dbres.code == "0")
                {
                    Session["SessionGuid"]    = Guid.NewGuid().ToString();
                    Session["UserId"]         = dbres.UserId;
                    Session["RoleId"]         = dbres.RoleId;
                    Session["AgentId"]        = dbres.AgentId;
                    Session["ParentId"]       = dbres.ParentId;
                    Session["UserName"]       = dbres.UserName;
                    Session["FullName"]       = dbres.FullName;
                    Session["UserType"]       = dbres.UserType;
                    Session["KycStatus"]      = dbres.KycStatus;
                    Session["FirstTimeLogin"] = dbres.FirstTimeLogin;
                    Session["IsPrimaryUser"]  = dbres.IsPrimaryUser;


                    var    menus = _login.GetMenus(common.UserName);
                    string areaName = "", dashboard_name = "Index";
                    if (dbres.UserType == "Admin" || dbres.UserType == "Distributor" || dbres.UserType == "Sub-Distributor")
                    {
                        areaName = "Admin";
                        if (dbres.UserType == "Distributor")
                        {
                            dashboard_name = "Dashboard2";
                        }
                        else if (dbres.UserType == "Sub-Distributor")
                        {
                            dashboard_name = "Dashboard3";
                        }
                    }
                    else if (dbres.UserType != null && (dbres.UserType.ToLower() == "walletuser" || dbres.UserType.ToLower() == "merchant" || dbres.UserType.ToLower() == "agent" || dbres.UserType.ToLower() == "sub-agent"))
                    {
                        areaName = "Client";;
                        if (dbres.KycStatus.ToUpper() == "APPROVED")
                        {
                            Session["KycStatus"] = "a";
                        }
                        else if (dbres.KycStatus.ToUpper() == "PENDING")
                        {
                            Session["KycStatus"] = "p";
                        }
                        else if (dbres.KycStatus.ToUpper() == "REJECTED")
                        {
                            Session["KycStatus"] = "r";
                        }
                        else
                        {
                            Session["KycStatus"] = "n";//N
                        }
                    }
                    var functions = _login.GetApplicatinFunction(dbres.RoleId, true);
                    _login.updateSessionId(Session["UserName"].ToString(), Session.SessionID);
                    Session["Menus"]     = menus.menu;
                    Session["Functions"] = functions;
                    return(new Tuple <string, string, string>(dashboard_name, "Home", areaName));
                }
                TempData["msg"] = dbres.message;
                return(new Tuple <string, string, string>("Index", "Home", ""));
            }
            catch (Exception)
            {
                TempData["msg"] = "Something Went Wrong";
                return(new Tuple <string, string, string>("Index", "Home", ""));
            }
        }
 protected override bool IsValidRequestString(System.Web.HttpContext context, string value, System.Web.Util.RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)
 {
     validationFailureIndex = -1; return(true);
 }
Example #59
0
        private void ProcessOrderAdd(System.Web.HttpContext context)
        {
            OrderInfo orderInfo = new OrderInfo();

            orderInfo.OrderId       = this.GenerateOrderId();
            orderInfo.TaobaoOrderId = context.Request.Form["TaobaoOrderId"];
            orderInfo.Remark        = context.Request.Form["BuyerMemo"] + context.Request.Form["BuyerMessage"];
            string text = context.Request.Form["SellerFlag"];

            if (!string.IsNullOrEmpty(text) && text != "0")
            {
                orderInfo.ManagerMark = new OrderMark?((OrderMark)int.Parse(text));
            }
            orderInfo.ManagerRemark      = context.Request.Form["SellerMemo"];
            orderInfo.OrderDate          = System.DateTime.Parse(context.Request.Form["OrderDate"]);
            orderInfo.PayDate            = System.DateTime.Parse(context.Request.Form["PayDate"]);
            orderInfo.UserId             = 1100;
            orderInfo.RealName           = (orderInfo.Username = context.Request.Form["Username"]);
            orderInfo.EmailAddress       = context.Request.Form["EmailAddress"];
            orderInfo.ShipTo             = context.Request.Form["ShipTo"];
            orderInfo.ShippingRegion     = context.Request.Form["ReceiverState"] + context.Request.Form["ReceiverCity"] + context.Request.Form["ReceiverDistrict"];
            orderInfo.RegionId           = RegionHelper.GetRegionId(context.Request.Form["ReceiverDistrict"], context.Request.Form["ReceiverCity"], context.Request.Form["ReceiverState"]);
            orderInfo.Address            = context.Request.Form["ReceiverAddress"];
            orderInfo.TelPhone           = context.Request.Form["TelPhone"];
            orderInfo.CellPhone          = context.Request.Form["CellPhone"];
            orderInfo.ZipCode            = context.Request.Form["ZipCode"];
            orderInfo.RealShippingModeId = (orderInfo.ShippingModeId = 0);
            orderInfo.RealModeName       = (orderInfo.ModeName = context.Request.Form["ModeName"]);
            orderInfo.PaymentType        = "支付宝担宝交易";
            orderInfo.Gateway            = "Ecdev.plugins.payment.alipayassure.assurerequest";
            orderInfo.PayCharge          = 0m;
            orderInfo.AdjustedDiscount   = 0m;
            string text2 = context.Request.Form["Products"];

            if (string.IsNullOrEmpty(text2))
            {
                context.Response.Write("-1");
                return;
            }
            string[] array = text2.Split(new char[]
            {
                '|'
            });
            if (array.Length <= 0)
            {
                context.Response.Write("-2");
                return;
            }
            string[] array2 = array;
            for (int i = 0; i < array2.Length; i++)
            {
                string   text3  = array2[i];
                string[] array3 = text3.Split(new char[]
                {
                    ','
                });
                LineItemInfo lineItemInfo = new LineItemInfo();
                int          productId    = 0;
                int.TryParse(array3[1], out productId);
                int shipmentQuantity = 1;
                int.TryParse(array3[3], out shipmentQuantity);
                lineItemInfo.SkuId           = array3[0];
                lineItemInfo.ProductId       = productId;
                lineItemInfo.SKU             = array3[2];
                lineItemInfo.Quantity        = (lineItemInfo.ShipmentQuantity = shipmentQuantity);
                lineItemInfo.ItemCostPrice   = (lineItemInfo.ItemAdjustedPrice = decimal.Parse(array3[4]));
                lineItemInfo.ItemListPrice   = decimal.Parse(array3[5]);
                lineItemInfo.ItemDescription = System.Web.HttpUtility.UrlDecode(array3[6]);
                lineItemInfo.ThumbnailsUrl   = array3[7];
                lineItemInfo.ItemWeight      = 0m;
                lineItemInfo.SKUContent      = array3[8];
                lineItemInfo.PromotionId     = 0;
                lineItemInfo.PromotionName   = "";
                orderInfo.LineItems.Add(lineItemInfo.SkuId, lineItemInfo);
            }
            orderInfo.AdjustedFreight = (orderInfo.Freight = decimal.Parse(context.Request.Form["PostFee"]));
            orderInfo.OrderStatus     = OrderStatus.BuyerAlreadyPaid;
            orderInfo.RefundStatus    = RefundStatus.None;
            //orderInfo.OrderSource = OrderSource.Taobao;
            if (ShoppingProcessor.CreateOrder(orderInfo, false, true))
            {
                context.Response.Write("1");
                return;
            }
            context.Response.Write("0");
        }
 /// <summary>
 /// Locks a session item and returns it from the database.
 /// </summary>
 /// <param name="context">The HttpContext object for the current request.</param>
 /// <param name="id">The session ID for the current request.</param>
 /// <param name="locked">
 /// <c>true</c> if the session item is locked in the database; otherwise, <c>false</c>.
 /// </param>
 /// <param name="lockAge">
 /// TimeSpan object that indicates the amount of time the session item has been locked in the database.
 /// </param>
 /// <param name="lockId">
 /// A lock identifier object.
 /// </param>
 /// <param name="actions">
 /// A <see cref="SessionStateActions"/> enumeration value that indicates whether or
 /// not the session is uninitialized and cookieless.
 /// </param>
 /// <returns></returns>
 public override SessionStateStoreData GetItemExclusive(System.Web.HttpContext context, string id,
                                                        out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions)
 {
     return(GetSessionStoreItem(true, context, id, out locked, out lockAge, out lockId, out actions));
 }