Exemplo n.º 1
0
        public HttpRequest(HttpListenerRequest listenerRequest)
        {
            _request = listenerRequest;
            _formData = new FormData(listenerRequest);

            LoadFormData();
        }
Exemplo n.º 2
0
        //[TestMethod]
        public void loginTest()
        {
            String responseContent = httpClient.SendHttpGetAndReturnResponseContent("http://parafia.biz/");
            String csrf = HtmlUtils.GetStringValueByXPathExpression(responseContent, "//input[@name='login_csrf']");

            FormData formData = new FormData();
            formData.addValue("formo_login_form", "login_form");
            formData.addValue("login_csrf", csrf);
            formData.addValue("user_name", user);
            formData.addValue("user_pass", passwd);
            formData.addValue("login_submit", "");

            responseContent = httpClient.SendHttpPostAndReturnResponseContent("http://parafia.biz/", formData);

            String errorMessage = HtmlUtils.GetStringValueByXPathExpression(responseContent, "//div[@class='form-error']/text()");

            if (!String.IsNullOrEmpty(errorMessage))
            {
                Assert.Fail();
            }
            else
            {
                Attributes att = new Attributes(responseContent);
            }
        }
Exemplo n.º 3
0
        public static Stream GetPostResponseStream(string requestUri,
            FormData data)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
                "https://www.douban.com" + requestUri);
            request.Method = "POST";
            request.ProtocolVersion = HttpVersion.Version11;

            request.Headers.Add("Origin", "onering://radio");
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1) "
                + "AppleWebKit/535.19 "
                + "(KHTML, like Gecko) Chrome/18.0.1025.151 Safari/535.19";

            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "application/json, text/javascript, */*; q=0.01";
            request.KeepAlive = true;

            request.CookieContainer = s_cookies;

            using (StreamWriter writer = new StreamWriter(
                request.GetRequestStream()))
            {
                writer.Write(data.GetFormString());
                writer.Close();
            }

            return request.GetResponse().GetResponseStream();
        }
        public void DoSomething(MarketingData data)
        {
            var formFields = new List<FormField>();
            formFields.Add(new FormField
            {
                FieldName = "First Name",
                FieldValue = data.FirstName
            });
            formFields.Add(new FormField
            {
                FieldName = "Last Name",
                FieldValue = data.LastName
            });
            formFields.Add(new FormField
            {
                FieldName = "Email",
                FieldValue = data.Email
            });

            FormData formData = new FormData();
            formData.FormId = MY_WFFM_FORM_ITEM_ID;
            formData.Fields = formFields;


            using (WebClient client = new WebClient())
            {
                client.UploadValues(RemoteUrl, "POST", formData);
            }
        }
Exemplo n.º 5
0
 public override void AddData(FormData data)
 {
     if (Value == null)
         data.Add(Name, string.Empty);
     else
         data.Add(Name, Value);
 }
Exemplo n.º 6
0
        public Form1()
        {
            string assembly_main_dir = @Directory.GetCurrentDirectory();
            ConfigSettings.InitConfigSettings(assembly_main_dir);

            SingletonFactory.LOG.Log("Test string", LoggerLevel.HIGH);
            SingletonFactory.LOG.Log("Testing components", LoggerLevel.MID, ComponentType.Animation);
            SingletonFactory.LOG.Log("This should log", ComponentType.Rendering);
            SingletonFactory.LOG.Log("This should log", ComponentType.Collision);
            SingletonFactory.LOG.Log("This should log", ComponentType.Animation);
            SingletonFactory.LOG.Log("This shouldn't log", ComponentType.Physics);

            _formData = SingletonFactory.GetFormData();
            InitializeComponent();
            _openGLControl.InitializeContexts();

            _input.Mouse = new Mouse(this, _openGLControl);
            _input.Keyboard = new Keyboard(_openGLControl);

            InitializeDisplay();
            InitializeDevIl();
            InitializeFonts();
            InitializeGameStates();

            _fastLoop = new FastLoop(GameLoop);
        }
Exemplo n.º 7
0
 public override void AddData(FormData data)
 {
     foreach (Option opt in options)
     {
         if (opt.Selected)
             data.Add(Name, opt.Value);
     }
 }
Exemplo n.º 8
0
 public static HttpWebRequest SendPost(String url, CookieContainer cookieContainer, FormData formData, int timeout)
 {
     HttpWebRequest request = DefaultPostHttpRequest(url);
     request.CookieContainer = cookieContainer;
     request.Timeout = timeout;
     WriteFormData(request, formData);
     return request;
 }
Exemplo n.º 9
0
 public static HttpWebRequest SendPostWithoutRedirection(String url, CookieContainer cookieContainer, FormData formData)
 {
     HttpWebRequest request = DefaultPostHttpRequest(url);
     request.AllowAutoRedirect = false;
     request.CookieContainer = cookieContainer;
     WriteFormData(request, formData);
     return request;
 }
Exemplo n.º 10
0
 public ActionResult Index(FormData data)
 {
     if (ModelState.IsValid)
     {
         db.Data.Add(new FormData { Name = data.Name });
         db.SaveChanges();
     }
     return RedirectToAction("Index");
 }
Exemplo n.º 11
0
        public static JResponse GetPostResponse(string requestUri,
            FormData data)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(
                typeof(JResponse));

            return (JResponse)ser.ReadObject(GetPostResponseStream(
                requestUri, data));
        }
Exemplo n.º 12
0
        public async Task<HttpResponseMessage> PostAsync(FormData data)
        {
            if (data == null)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, "Could not parse post data");
            }

            return await this.GetResponse(data);
        }
        public async Task Gets_validators_from_service_provider() {
			var form = new FormData {
				{ "test.Name", null }
			};

			var result = await GetErrors("Test1", form);

			result.IsValidField("test.Name").ShouldBeFalse();
			result.GetError("test.Name").ShouldEqual("Validation Failed");
		}
Exemplo n.º 14
0
        public async Task<HttpResponseMessage> GetAsync(string data = "", HttpStatusCode status = HttpStatusCode.OK, int delay = 0)
        {
            var formData = new FormData()
            {
                Response = data,
                Delay = delay,
                Status = status
            };

            return await this.GetResponse(formData);
        }
Exemplo n.º 15
0
        private async Task<HttpResponseMessage> GetResponse(FormData data)
        {
            if (data.Delay > 0)
            {
                await Task.Delay(data.Delay);
            }

            var response = Request.CreateResponse(data.Status);
            response.Content = new StringContent(data.Response);
            return response;
        }
Exemplo n.º 16
0
		static void SendFile(ButtonIcon bt, FileInput input)
		{
			bt.Disabled = true;

			var fd = new FormData ();  
			fd.Append ("userfile", input.Files [0]);  

			var rq = fd.Send ("SaveFileUrl");  
			rq.Done (() => "File Uploaded".LogSuccess (5000));  
			rq.Fail (()=> "{0}:{1}".Fmt(rq.Status, rq.StatusText).LogError());
			rq.Always (() => bt.Disabled=false);  

		}
Exemplo n.º 17
0
        // public CheckResult retCheck;
        /// <summary>
        /// コンストラクタ
        /// </summary>
        /// <param name="checker">コピーコンストラクタ(ライトコピー)</param>
        public Checker(Checker checker)
        {
            //retCheck = new CheckResult();
            loginUrl = checker._loginUrl;
            homeUrl = checker._homeUrl;
            getOnlyUrl = checker._getOnlyUrl;
            formdata = checker._formdata;

            //参照渡し
            formdatas = checker.formdatas;
            checkResult = checker.checkResult;
            firstResponse = checker.firstResponse;
        }
Exemplo n.º 18
0
        public FormData Submit(SubmitButton button)
        {
            FormData formData = new FormData();

            foreach (FormElement el in elements)
            {
                if (el.IsSuccessful || object.ReferenceEquals(button, el))
                {
                    el.AddData(formData);
                }
            }

            return formData;
        }
Exemplo n.º 19
0
 public static HttpWebRequest SendPost(String url, CookieContainer cookieContainer, FormData formData, NameValueCollection headers)
 {
     HttpWebRequest request = DefaultPostHttpRequest(url);
     request.Headers.Add(headers);
     request.CookieContainer = cookieContainer;
     /*RequestCachePolicy policy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
     request.CachePolicy = policy;
     request.KeepAlive = true;
     request.Host = "trade.plus500.com";
     request.Referer = "https://trade.plus500.com/Login?forceDisplay=True&IsRealMode=False";
        */
     WriteFormData(request, formData);
     return request;
 }
Exemplo n.º 20
0
 public ActionResult Edit(FormData data)
 {
     if (ModelState.IsValid)
     {
         var oldData = db.Data.Find(data.Id);
         if (oldData != null)
         {
             oldData.Name = data.Name;
             db.SaveChanges();
             return RedirectToAction("Index");
         }
     }
     return RedirectToAction("Edit");
 }
Exemplo n.º 21
0
 public override void AddData(FormData data)
 {
     if (Name != null)
     {
         data.Add(Name + ".x", "1");
         data.Add(Name + ".y", "1");
     }
     else
     {
         data.Add("x", "1");
         data.Add("y", "1");
     }
     base.AddData(data);
 }
Exemplo n.º 22
0
        public void AppendForm()
        {
            var form = new FormData();

            form.Add("a", "1");

            Assert.Equal("a=1", form.ToString());

            form.Add("b", "2");

            Assert.Equal("a=1&b=2", form.ToString());


            
        }
Exemplo n.º 23
0
 public void ToStringTest()
 {
     var formData = new FormData
     {
         {"text_to_transcribe", "You there"},
         {"submit", "Show transcription"},
         {"output_dialect", "am"},
         {"output_style", "only_tr"},
         {"weak_forms", "on"},
         {"preBracket", "["},
         {"postBracket", "]"}
     };
     const string expected = "text_to_transcribe=You+there&submit=Show+transcription&output_dialect=am&output_style=only_tr&weak_forms=on&preBracket=%5b&postBracket=%5d";
     string actual = formData.ToString();
     Assert.AreEqual(expected, actual);
 }
Exemplo n.º 24
0
        public void SendRequestTest()
        {
            FormData formData = new FormData();
            formData.addValue("formo_login_form", "login_form");
            formData.addValue("login_csrf", "128e641cd470cb2f08484d309211e0f8");
            formData.addValue("user_name", "sairo");
            formData.addValue("login_submit", "");

            WebProxy webProxy = new WebProxy("126.179.0.200", 3128);

            DefaultHttpClient httpClient = new DefaultHttpClient();
            httpClient.SetWebProxy = webProxy;

            HttpWebResponse loginResponse =  httpClient.HttpPost("http://parafia.biz/", formData);

            HttpWebResponse test = httpClient.HttpGet("http://parafia.biz/units/buy/4/amount/1");

            //Console.WriteLine(response.StatusCode);
        }
Exemplo n.º 25
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                FormData dataObject = new FormData();

                if (TryUpdateModel(dataObject, new FormValueProvider(ModelBindingExecutionContext)))
                {

                    if (dataObject.Name == "Bob")
                    {
                        System.Diagnostics.Debugger.Break();
                    }

                    target.InnerText = String.Format("Name: {0}, City: {1}",
                        dataObject.Name, dataObject.City);
                }
            }
        }
Exemplo n.º 26
0
        /// <summary>
        ///     上传媒体。
        ///     注意:如果上传失败,会抛出WxMenuException异常
        /// </summary>
        /// <param name="media"></param>
        /// <returns></returns>
        public RemoteMedia Upload(LocalMedia media)
        {
            var checkRet = MediaChecker(media);
            if (!checkRet.IsSuccess)
                throw new WxException(-9999, checkRet.ErrMsg); //todo:考虑是否设计新的Exception类,以区分异常是由微信抛出还是本地抛出

            var param = new FormData
            {
                {"access_token", AccessToken},
                {"type", media.MediaType}
            };
            var rs = new HttpHelper(UploadUrl).Upload(param, media.MediaPath);
            var ret = JsonConvert.DeserializeObject<RemoteMedia>(rs);
            if (string.IsNullOrEmpty(ret.MediaID))
            {
                var ex = JsonConvert.DeserializeObject<BasicResult>(rs);
                throw new WxException(ex);
            }
            return ret;
        }
Exemplo n.º 27
0
        public void login(String login, String password)
        {
            FormData formData = new FormData();
            formData.addValue("isRealMode", "False");
            formData.addValue("userName", login);
            formData.addValue("password", password);
            formData.addValue("savePassword", "false");

            HttpWebResponse response2 = httpClient.HttpGet("https://trade.plus500.com/");

            String MachineId = "";

            Random rand = new Random();
            for (int i = 0; i < 32; i++)
            {
                MachineId += "0123456789abcdef".Substring((int)Math.Floor(rand.NextDouble() * 16), 1);
            }

            String base64String = Convert.ToBase64String(Encoding.UTF8.GetBytes(password.ToCharArray()));

            httpClient.AddCookie(new Cookie("MachineID", MachineId, "/", "trade.plus500.com"));
            httpClient.AddCookie(new Cookie("IsRealMode", "False", "/", "trade.plus500.com"));
            httpClient.AddCookie(new Cookie("UserName", HttpUtility.UrlEncode(login), "/", "trade.plus500.com"));
            httpClient.AddCookie(new Cookie("ChoseAccountModeActively", "True", "/", "trade.plus500.com"));
            httpClient.AddCookie(new Cookie("Password", base64String, "/", "trade.plus500.com"));
            httpClient.AddCookie(new Cookie("PasswordHidden" , "1", "/", "trade.plus500.com"));
            httpClient.AddCookie(new Cookie("PasswordDontPersist", "1", "/", "trade.plus500.com"));

            HttpWebResponse response1 = httpClient.HttpPost("https://trade.plus500.com/Login?forceDisplay=True&IsRealMode=False", formData);

            //HttpWebResponse response1 = httpClient.HttpGet("http://trade.plus500.com/Trade");

            httpClient.CookieContainer = prepareCookies(httpClient.CookieContainer);

            String content = httpClient.SendHttpGetAndReturnResponseContent("http://trade.plus500.com/Trade");

            HtmlNode node = HtmlUtils.GetSingleNodeByXPathExpression(content, "//div[@id='session_id']");
        }
Exemplo n.º 28
0
 public int AddFormData(FormData model)
 {
     string cmdText = @"
     DECLARE @NEWID INT
     insert into FormData
     (
         dataid,
         formtype,
         formdata,
         createtime
     )
     values
     (
         @dataid,
         @formtype,
         @formdata,
         getdate()
     )
     SET @NEWID=@@IDENTITY
     SELECT @NEWID";
     SqlParameter[] parameters =
     {
         SqlParamHelper.MakeInParam("@dataid",SqlDbType.Int,4,model.dataid),
         SqlParamHelper.MakeInParam("@formtype",SqlDbType.SmallInt,2,model.formtype.ToInt32()),
         SqlParamHelper.MakeInParam("@formdata",SqlDbType.Text,int.MaxValue,model.formdata)
     };
     int id = 0;
     using (IDataReader dataReader = SqlHelper.ExecuteReader(WriteConnectionString,CommandType.Text,cmdText,parameters)){
         if(dataReader.Read()){
             object obj = dataReader[0];
             if(obj != null && obj != DBNull.Value){
                 id = Convert.ToInt32(obj);
             }
         }
     }
     return id;
 }
Exemplo n.º 29
0
        public async Task When_global_action_context_interceptor_specified_Intercepts_validation_for_razor_pages()
        {
            var form = new FormData {
                { "Email", "foo" },
                { "Surname", "foo" },
                { "Forename", "foo" },
            };
            var client = _webApp
                         .WithFluentValidation(fv => {
                fv.ValidatorFactoryType = typeof(AttributedValidatorFactory);
                fv.ImplicitlyValidateChildProperties = true;
            })
                         .WithWebHostBuilder(builder => builder.ConfigureServices(
                                                 services => services.AddSingleton <IActionContextValidatorInterceptor, SimpleActionContextPropertyInterceptor>())
                                             )
                         .CreateClient();
            var response = await client.PostResponse($"/RulesetTest", form);

            var result = JsonConvert.DeserializeObject <List <SimpleError> >(response);

            result.IsValidField("Forename").ShouldBeFalse();
            result.IsValidField("Surname").ShouldBeFalse();
            result.IsValidField("Email").ShouldBeTrue();
        }
Exemplo n.º 30
0
        public FormData GetFormData()
        {
            OAuthWXConfigInfo config = ConfigService <OAuthWXConfigInfo> .GetConfig(string.Concat(WXLoginPlugin.WXWorkDirectory, "\\Config\\OAuthWXConfig.config"));

            FormData formDatum = new FormData();

            FormData.FormItem[] formItemArray = new FormData.FormItem[2];
            FormData.FormItem   formItem      = new FormData.FormItem();
            formItem.DisplayName = "AppId";
            formItem.Name        = "AppId";
            formItem.IsRequired  = true;
            formItem.Type        = FormData.FormItemType.text;
            formItem.Value       = config.AppId;
            formItemArray[0]     = formItem;
            FormData.FormItem formItem1 = new FormData.FormItem();
            formItem1.DisplayName = "AppSecret";
            formItem1.Name        = "AppSecret";
            formItem1.IsRequired  = true;
            formItem1.Type        = FormData.FormItemType.text;
            formItem1.Value       = config.AppSecret;
            formItemArray[1]      = formItem1;
            formDatum.Items       = formItemArray;
            return(formDatum);
        }
Exemplo n.º 31
0
    public void FindWindowOnSceneOrCreate(FormData formData)
    {
        UIConsts.FORM_ID formID   = formData.Id;
        GameObject       newForm  = null;
        string           formName = formID.ToString();

        foreach (var w in WindowsAvailableAtStart)
        {
            if (w.name == formName)
            {
                newForm = w;
                break;
            }
        }
        if (newForm != null)
        {
            newForm.GetComponent <BaseUIController>().CreationMethod = formData.CreationMethod;
            _uiList.Add(formID, newForm);
        }
        else
        {
            CreateWindow(formData);
        }
    }
        /// <summary>
        /// Read the non-file contents as form data.
        /// </summary>
        /// <returns></returns>
        public override async Task ExecutePostProcessingAsync()
        {
            // Find instances of non-file HttpContents and read them asynchronously
            // to get the string content and then add that as form data
            for (int index = 0; index < Contents.Count; index++)
            {
                if (_isFormData[index])
                {
                    HttpContent formContent = Contents[index];
                    // Extract name from Content-Disposition header. We know from earlier that the header is present.
                    ContentDispositionHeaderValue contentDisposition = formContent.Headers.ContentDisposition;
                    string formFieldName = UnquoteToken(contentDisposition.Name) ?? String.Empty;

                    // Read the contents as string data and add to form data
                    string formFieldValue = await formContent.ReadAsStringAsync();

                    FormData.Add(formFieldName, formFieldValue);
                }
                else
                {
                    _fileContents.Add(Contents[index]);
                }
            }
        }
Exemplo n.º 33
0
        /// <summary>
        ///  http://localhost:9517/Api/PLF/?schoolYear=20182019schoolCode=0290
        ///  will return PLF form all Title and content items by school anf year.
        /// </summary>
        /// <param name="schoolYear"></param>
        /// <param name="schoolCode"></param>
        /// <returns>PLF Form content list  </returns>
        // GET: api/PLF
        public IEnumerable <FormContent> Get(string schoolYear, string schoolCode)
        {
            List <FormContent> list = FormData.ListofContent(schoolYear, schoolCode);

            return(list);
        }
Exemplo n.º 34
0
        /// <summary>
        ///  http://localhost:9517/Api/PLF
        ///  will return PLF form all Title and content items by school anf year.
        /// </summary>

        /// <returns>PLF Form content list  </returns>
        // GET: api/PLF
        public IEnumerable <FormContent> Get()
        {
            List <FormContent> list = FormData.ListofContent("20182019", "0290");

            return(list);
        }
Exemplo n.º 35
0
 void Awake()
 {
     Instance = this;
 }
Exemplo n.º 36
0
        public ActionResult EncodeText(FormData formData, FormCollection form)
        {
            SelectList items = new SelectList(ciphers);

            // Caesar cipher encode
            if (Request.Form["Ciphers"] == "Caesar cipher" && formData.tbkey != "")
            {
                if (formData.EncodedText != "")
                {
                    formData.EncodedText = "";
                }
                try
                {
                    foreach (var item in charsToRemove)
                    {
                        formData.YourText = formData.YourText.Replace(item, string.Empty);
                    }

                    char[] text = formData.YourText.ToCharArray().Where(s => !char.IsWhiteSpace(s)).ToArray();

                    for (int i = 0; i < text.Length; i++)
                    {
                        for (int j = 0; j <= alphabet.Length && j <= alphabetUpper.Length; j++)
                        {
                            if (text[i].ToString() == alphabet[j].ToString() || text[i].ToString() == alphabetUpper[j].ToString())
                            {
                                char.ToLower(text[i]);

                                formData.EncodedText += Convert.ToChar(alphabet[(j + Convert.ToInt32(formData.tbkey)) % alphabet.Length]);
                                break;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    ViewBag.Exception = ex.Message;
                }
            }

            //  Vigenere cipher encode
            if (Request.Form["Ciphers"] == "Vigenere cipher")
            {
                if (formData.EncodedText != "")
                {
                    formData.EncodedText = "";
                }
                foreach (var item in charsToRemove)
                {
                    formData.YourText = formData.YourText.Replace(item, string.Empty);
                }
                char[] text = formData.YourText.ToCharArray().Where(s => !char.IsWhiteSpace(s)).ToArray();
                char[] key  = formData.tbkey.ToCharArray();
                try
                {
                    char[,] Vigenere_Table = new char[26, 26];

                    int temp = 0;
                    for (int i = 0; i < alphabet.Length; i++)
                    {
                        for (int j = 0; j < 26; j++)
                        {
                            temp = j + i;
                            if (temp >= 26)
                            {
                                temp = temp % 26;
                            }
                            Vigenere_Table[i, j] = alphabet[temp];
                        }
                    }

                    for (int t = 0, k = 0; t < text.Length || k < key.Length; t++, k++)
                    {
                        if (t >= text.Length)
                        {
                            break;
                        }
                        if (k == key.Length /*t % key.Length == 0*/)
                        {
                            k = 0;
                            for (int y = 0; y <= alphabet.Length; y++)
                            {
                                if (text[t].ToString() == alphabet[y].ToString() || text[t].ToString() == alphabetUpper[y].ToString())
                                {
                                    char.ToLower(text[t]);
                                    Ytext = y;
                                    for (int x = 0; x <= alphabet.Length; x++)
                                    {
                                        if (key[k].ToString() == alphabet[x].ToString())
                                        {
                                            Xkey = x;
                                            formData.EncodedText += Vigenere_Table[Ytext, Xkey].ToString();
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                        else
                        {
                            for (int y = 0; y <= alphabet.Length; y++)
                            {
                                if (text[t].ToString() == alphabet[y].ToString() || text[t].ToString() == alphabetUpper[y].ToString())
                                {
                                    char.ToLower(text[t]);
                                    Ytext = y;
                                    for (int x = 0; x <= alphabet.Length; x++)
                                    {
                                        if (key[k].ToString() == alphabet[x].ToString())
                                        {
                                            Xkey = x;
                                            formData.EncodedText += Vigenere_Table[Ytext, Xkey].ToString();
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    ViewBag.Exception = ex.Message;
                }
            }

            ViewBag.Ciphers = items;
            return(View(formData));
        }
Exemplo n.º 37
0
 public FormPage(FormData formData)
 {
     InitializeComponent();
 }
Exemplo n.º 38
0
 /// <summary>
 ///  http://localhost:9517/api/PLF/?schoolYear=20182019schoolCode=0290itemCode=PLP11value=myinputtext
 ///  by provide the value the Web API will save the value to database and return save or update action result.
 /// </summary>
 /// <param name="schoolYear"></param>
 /// <param name="schoolCode"></param>
 /// <param name="itemCode"></param>
 /// <param name="value"></param>
 /// <returns>PLF Form save content and get save result back</returns>
 // GET: api/PLF/itemCode/value
 public string Get(string schoolYear, string schoolCode, string itemCode, string value)
 {
     return(FormData.Content("Content", "", "", schoolYear, schoolCode, itemCode, value));
 }
Exemplo n.º 39
0
        protected string RenderJavascript()
        {
            StringBuilder script = new StringBuilder();

            script.Append(" $(function () {").AppendLine();
            //多语弹出框关闭
            script.AppendLine(" $(\".multilangpopoverclose\").on(ace.click_event, function () {     $(this).closest(\".popover\").css(\"display\",\"none\");  });");
            //参照弹出事件、上传附件、数值控件
            //开启textarea 校验
            bool hasTextArea = false;
            //开启jqueryvalidate校验的条件
            bool needValidate = false;

            foreach (FapField field in formFields)
            {
                FapColumn column = field.CurrentColumn;
                if (column.ColName == "Id" || column.ColName == "Fid" || column.ShowAble == 0)
                {
                    continue;
                }
                if (!hasTextArea && column.CtrlType == FapColumn.CTRL_TYPE_MEMO)
                {
                    hasTextArea = true;
                }
                if (!needValidate && ((column.NullAble == 0 && column.ShowAble == 1) || column.RemoteChkURL.IsPresent()))
                {
                    needValidate = true;
                }
                #region 日期
                if (column.CtrlType == FapColumn.CTRL_TYPE_DATE)
                {
                    string model      = "0";
                    string dateFormat = column.DisplayFormat;
                    string minDate    = "1900-1-1";
                    string maxDate    = "2999-12-12";
                    if (dateFormat.IsMissing())
                    {
                        dateFormat = "yyyy-mm-dd";
                        model      = "0";
                    }
                    else if (dateFormat.Length > 4 && dateFormat.Length < 10)
                    {
                        dateFormat = "yyyy-mm";
                        model      = "1";
                    }
                    else
                    {
                        dateFormat = "yyyy";
                        model      = "2";
                    }
                    if (column.MinValue != 0)
                    {
                        minDate = DateTimeUtils.DateFormat(DateTime.Now.AddDays((double)column.MinValue));
                    }
                    if (column.MaxValue != 0)
                    {
                        maxDate = DateTimeUtils.DateFormat(DateTime.Now.AddDays((double)column.MaxValue));
                    }
                    if (dateFormat == "yyyy-mm-dd")
                    {
                        script.AppendLine(" $(\"###formid## #" + column.ColName + "\").scroller('destroy').scroller($.extend({preset:'date', minDate:moment('" + minDate + "').toDate(),maxDate:moment('" + maxDate + "').toDate()},{ theme: 'android-ics light', mode: 'scroller', display:'modal', lang: 'zh' }));");
                    }
                    else
                    {
                        script.AppendLine("$(\"###formid## #" + column.ColName + "\").datePicker({  followOffset: [0, 24],onselect:function(date){ var formatDate = DatePicker.formatDate(date, '" + dateFormat + "');this.shell.val(formatDate).change();  return false;},minDate:'" + minDate + "',maxDate:'" + maxDate + "', altFormat:'" + dateFormat + "',showMode:" + model + " }).next().on(ace.click_event, function () {$(this).prev().focus(); });");
                    }
                }
                else if (column.CtrlType == FapColumn.CTRL_TYPE_DATETIME)
                {
                    //moment.js的格式
                    //string format = column.DisplayFormat;
                    //string startDate = "1900-1-1";
                    //string endDate = "2999-12-12";
                    //string startView = "2";
                    //if (column.MinValue.HasValue)
                    //{
                    //    startDate = DateTime.Now.AddDays((column.MinValue).ToDouble()).ToString(PublicUtils.DateFormat);
                    //}
                    //if (column.MaxValue.HasValue)
                    //{
                    //    endDate = DateTime.Now.AddDays((column.MaxValue).ToDouble()).ToString(PublicUtils.DateFormat);
                    //}
                    //if (format.IsMissing())
                    //{
                    //    format = "yyyy-mm-dd hh:ii:ss";
                    //}
                    //else if (format.EqualsWithIgnoreCase("HH:mm"))
                    //{
                    //    format = "hh:ii";
                    //    startView = "0";
                    //}


                    //script.AppendLine(" $(\"#" + column.ColName + "\").datetimepicker({ format:\"" + format + "\",startDate:'" + startDate + "',endDate:'" + endDate + "',startView:" + startView + ",todayBtn:true,todayHighlight:true, language: \"zh-CN\" }).next().on(ace.click_event, function () {            $(this).prev().focus();        });");

                    string format    = column.DisplayFormat;
                    string startDate = "1900-1-1";
                    string endDate   = "2999-12-12";

                    if (column.MinValue != 0)
                    {
                        startDate = DateTimeUtils.DateFormat(DateTime.Now.AddDays((double)column.MinValue));
                    }
                    if (column.MaxValue != 0)
                    {
                        endDate = DateTimeUtils.DateFormat(DateTime.Now.AddDays((double)column.MaxValue));
                    }
                    if (format.IsMissing())
                    {
                        //format = "datetime";
                        //script.AppendLine("opt.datetime = { preset : 'datetime', minDate:moment('" + startDate + "').toDate(), maxDate: minDate:moment('" + endDate + "').toDate() , stepMinute: 5  };");
                        script.AppendLine(" $(\"###formid## #" + column.ColName + "\").scroller('destroy').scroller($.extend({ preset:'datetime', minDate:moment('" + startDate + "').toDate(), maxDate:moment('" + endDate + "').toDate() , stepMinute: 5  }, { theme:'android-ics light', mode: 'scroller', display:'modal', lang: 'zh' }));");
                    }
                    else if (format.EqualsWithIgnoreCase("HH:mm"))
                    {
                        format = "time";
                        //script.AppendLine("opt.time = {preset : 'time'};");
                        script.AppendLine(" $(\"###formid## #" + column.ColName + "\").scroller('destroy').scroller($.extend({preset:'time'}, { theme: 'android-ics light', mode: 'scroller', display:'modal', lang: 'zh' }));");
                    }
                }
                #endregion

                #region 参照
                else if (column.CtrlType == FapColumn.CTRL_TYPE_REFERENCE && !field.ReadOnly)
                {
                    //去除自定义列
                    if (column.IsCustomColumn == 1)
                    {
                        continue;
                    }
                    //编码已经和地址一样了
                    string refUrl = column.RefType;
                    //if (column.RefType == "GRID")
                    //{
                    //    refUrl = "GridReference";
                    //}
                    //else if (column.RefType == "TREE")
                    //{
                    //    refUrl = "TreeReference";
                    //}
                    //else
                    //{
                    //    refUrl = "TreeGridReference";
                    //}
                    string dispalyName = _multiLangService.GetMultiLangValue(MultiLanguageOriginEnum.FapColumn, $"{column.TableName}_{column.ColName}");
                    script.AppendLine("$(\"###formid## #" + column.ColName + "MC\").next().on(ace.click_event, function(){");
                    //script.AppendLine("//不可编辑字段不能弹出");
                    script.AppendLine(" if($(this).prev().attr(\"disabled\")==\"disabled\"){return;}");
                    //扩展参考值,参照参数用
                    script.AppendLine("var extra=[];");

                    //针对某些参照要用表单上的控件数据
                    if (column.RefCondition.IsPresent())
                    {
                        //DeptUid='${DeptUid}',@后面为表单上的控件
                        string fieldName = "";
                        string pattern   = FapPlatformConstants.VariablePattern;
                        Regex  regex     = new Regex(pattern);
                        var    mat       = regex.Matches(column.RefCondition);
                        foreach (Match item in mat)
                        {
                            int length = item.ToString().Length - 3;
                            fieldName = item.ToString().Substring(2, length);
                            //fieldName = item.Groups[1].ToString();

                            FapColumn col = _fapColumns.FirstOrDefault(f => f.ColName.EqualsWithIgnoreCase(fieldName));
                            if (col != null)
                            {
                                script.AppendLine("var conv=$('#" + fieldName + "').val();if(conv==''){bootbox.alert('【" + _multiLangService.GetMultiLangValue(MultiLanguageOriginEnum.FapColumn, $"{col.TableName}_{col.ColName}") + "】为空,请先设置。');return;}");
                                script.AppendLine("extra.push('" + fieldName + "='+conv)");
                            }
                        }
                    }
                    script.AppendLine("loadRefMessageBox('" + dispalyName + "','##formid##','" + column.Fid + "','" + column.ColName + "','" + refUrl + "',extra)");
                    script.AppendLine("});");
                    script.AppendLine("$(\"###formid## #" + column.ColName + "MC\").on(ace.click_event,function(e){$(this).next().trigger(ace.click_event);e.preventDefault();});");
                }
                #endregion

                #region 附件

                else if (column.CtrlType == FapColumn.CTRL_TYPE_FILE)
                {
                    script.AppendLine("$(\"###formid## #file" + FormId + column.ColName + "\").on(ace.click_event, function () {");
                    string tempFid = UUIDUtils.Fid;
                    if (field.FieldValue.ToString().IsMissing())
                    {
                        field.FieldValue = tempFid;
                    }
                    script.AppendLine("loadFileMessageBox('" + tempFid + "','##formid##',initFile" + FormId.Replace('-', '_') + tempFid + ");");

                    script.AppendLine("});");
                    string allowExt = string.Empty;
                    if (column.FileSuffix.IsPresent())
                    {
                        List <string> suffix = column.FileSuffix.SplitComma();
                        if (suffix.Any())
                        {
                            allowExt = string.Join(",", suffix.Select(s => "'" + s + "'").ToList());
                        }
                    }
                    //建立初始化附件控件js函数
                    script.AppendLine("var initFile" + FormId.Replace('-', '_') + tempFid + "=function(){");
                    script.AppendLine("$(\"###formid##" + tempFid + "-FILE\").fileinput({");
                    script.AppendLine("language: language,");
                    script.AppendLine($"uploadUrl:\"{ _applicationContext.BaseUrl }/Component/UploadFile/{ field.FieldValue }\",");
                    //script.AppendLine("deleteUrl:\"http://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.ApplicationPath  + "/Api/Core/deletefile\",");
                    if (allowExt.IsPresent())
                    {
                        script.AppendLine($"allowedFileExtensions : [{ allowExt }],");
                    }
                    if (column.FileSize > 0)
                    {
                        script.AppendLine($"maxFileSize: {column.FileSize},");
                    }
                    script.AppendLine("uploadExtraData:{fid:'" + field.FieldValue + "'},");
                    script.AppendLine("allowedPreviewTypes: ['image', 'text'],");
                    script.AppendLine($"maxFileCount:{(column.FileCount == 0 ? 1 : column.FileCount)},");
                    script.AppendLine("showUpload: true,");
                    //script.AppendLine("showCaption: false,");
                    //script.AppendLine("overwriteInitial: false,");
                    script.AppendLine("slugCallback: function(filename) {");
                    script.AppendLine(" return filename.replace('(', '_').replace(']', '_');");
                    script.AppendLine("},");
                    //浏览按钮样式
                    //script.AppendLine("browseClass: \"btn btn-primary btn-block\",");
                    //浏览按钮图标
                    script.AppendLine("previewFileIcon: \"<i class='glyphicon glyphicon-king'></i>\"})");
                    //script.AppendLine(@".on('fileloaded', function(event, file, previewId, index, reader) {
                    //    var files =$(this).fileinput('getFileStack');
                    //    $(this).fileinput('uploadSingle',index,files,false);})");
                    script.AppendLine(@".on('fileuploaded', function (event, data, previewId, index) {  if(data.response.success==false){bootbox.alert(data.response.msg);}else{loadFileList('" + FormId + "', '" + column.ColName + "', '" + field.FieldValue.ToString() + "');                } });       ");
                    script.AppendLine("}");
                    if (_formStatus == FormStatus.Edit)
                    {
                        string bid = field.FieldValue.ToString();
                        script.AppendLine("loadFileList('" + FormId + "','" + column.ColName + "','" + bid + "');");
                    }
                }
                #endregion

                #region 图片头像
                else if (column.CtrlType == FapColumn.CTRL_TYPE_IMAGE && !field.ReadOnly)
                {
                    if (field.FieldValue.ToString().IsMissing())
                    {
                        field.FieldValue = UUIDUtils.Fid;
                    }
                    script.AppendLine("loadImageControl('avatar" + column.ColName + "')");
                }
                #endregion

                #region 富文本控件
                else if (column.CtrlType == FapColumn.CTRL_TYPE_RICHTEXTBOX)
                {
                    script.AppendLine("var wysiwyg_" + column.ColName + " =$(\"###formid## #" + column.ColName + ".wysiwyg-editor\").ace_wysiwyg({" + @"
						toolbar:
						[
                            'font',
			                null,
			                'fontSize',
			                null,
							'bold',
							'italic',
							'strikethrough',
							'underline',
							null,
                            'insertunorderedlist',
                            'insertorderedlist',
                            'outdent',
                            'indent', 
                            null,
							'justifyleft',
							'justifycenter',
							'justifyright',
							null,
							'createLink',
							'unlink',
							null,
                            'insertImage',
                            null,
                            'foreColor',
		                    null,
							'undo',
							'redo',
                            null,
						'viewSource'
						]
					}).prev().addClass('wysiwyg-style1');"                    );
                    //script.AppendLine("$(\"#frm-" + _id + " #" + column.ColName + "\").html('" + StringUtil.TextToHtml(field.FieldValue.ToString()) + "');");
                }
                #endregion

                #region 数值控件
                else if (column.CtrlType == FapColumn.CTRL_TYPE_INT || column.CtrlType == FapColumn.CTRL_TYPE_DOUBLE || column.CtrlType == FapColumn.CTRL_TYPE_MONEY)
                {
                    if (column.EditAble != 1)
                    {
                        continue;
                    }
                    int min = column.MinValue;
                    int max = column.MaxValue;
                    if (min == 0 && max == 0)
                    {
                        min = int.MinValue;
                        max = int.MaxValue;
                    }
                    string unit = "";
                    if (column.CtrlType == FapColumn.CTRL_TYPE_MONEY)
                    {
                        unit = " postfix: '¥'";
                    }
                    string step      = "1";
                    int    precision = column.ColPrecision;
                    if (precision > 0)
                    {
                        step = "0." + "1".PadLeft(precision, '0');
                    }
                    script.AppendLine(" $(\"###formid## input[name='" + column.ColName + "']\").TouchSpin({");
                    script.AppendLine(@"
                        min: " + min + @",
                        max: " + max + @",
                        step: " + step + @",
                        decimals: " + precision + @",
                        boostat: 5,
                        maxboostedstep: 10,
                     
                        " + unit + @"
                    });
                   ");
                }
                #endregion

                #region 数值范围
                else if (column.CtrlType == FapColumn.CTRL_TYPE_RANGE)
                {
                    StringBuilder sr = new StringBuilder("[");
                    for (int i = column.MinValue; i <= column.MaxValue; i++)
                    {
                        sr.Append($"{i},");
                    }
                    string r = sr.ToString().TrimEnd(',');
                    r += "]";
                    script.AppendLine(@"$('###formid## #" + column.ColName + @"').jRange({
                        from: " + column.MinValue + @",
                        to: " + column.MaxValue + @",
                        step: 1,
                        scale: " + r + @",
                        format: '%s',
                        width: 680,
                        disable:" + ((column.EditAble == 0 || field.ReadOnly) ? "true," : "false,") + @"
                        theme:'theme-blue',
                        showLabels: true,
                        isRange: true
                    });");
                }
                #endregion

                #region 籍贯

                else if (column.CtrlType == FapColumn.CTRL_TYPE_NATIVE)
                {
                    //籍贯
                    script.AppendLine("$(\"###formid## #" + column.ColName + "\").citypicker();");
                }

                #endregion

                #region 城市

                else if (column.CtrlType == FapColumn.CTRL_TYPE_CITY)
                {
                    //城市
                    script.AppendLine("$(\"###formid## #" + column.ColName + "\").cityselect();");
                }

                #endregion
                #region 评星级
                else if (column.CtrlType == FapColumn.CTRL_TYPE_STAR)
                {
                    if (field.FieldValue?.ToString().IsMissing() ?? true)
                    {
                        field.FieldValue = "0";
                    }
                    //评星级
                    script.AppendLine("if(!$(\"###formid## #" + column.ColName + "\").prop(\"disabled\")){ $(\"###formid## #rat-" + column.ColName + "\").raty({number: 5,score:" + field.FieldValue +
                                      @", cancel: true,  'starType' : 'i',
                    'click': function(score,evt) {" +
                                      "$(\"###formid## #" + column.ColName + "\").val(score);" +
                                      @"},					
                    })}else{" + "$(\"###formid## #rat-" + column.ColName + "\").raty({number: 5,score:" + field.FieldValue +
                                      @",  'starType' : 'i',readOnly: true			
                    })}");
                }
                #endregion
                #region 多語
                else if (column.CtrlType == FapColumn.CTRL_TYPE_TEXT && column.IsMultiLang == 1)
                {
                    string oriCtrl = column.ColName;

                    string ctrmultiLang = oriCtrl + _multiLangService.CurrentLanguageName;

                    script.AppendLine("$(\"###formid## #" + oriCtrl + "\").on(\"blur\",function(){$(\"###formid## #" + ctrmultiLang + "\").val($(this).val())}).next().on(ace.click_event, function(){");
                    script.AppendLine(" document.addEventListener(\"mousedown\", onMultiLangPoverMouseDown, false);");
                    script.AppendLine("var fid=$(this).data(\"fid\");");
                    script.AppendLine("var X1 = $(\"###formid## #" + oriCtrl + "\").offset().top-55;var Y1 =$(\"###formid## #" + oriCtrl + "\").offset().left;");
                    script.AppendLine("var bg=$(\"#\"+fid).closest(\".modal-lg\");var top=X1;var left=Y1");
                    script.AppendLine("if(bg){ var bgo=bg.offset();   top=X1-bgo.top;left=Y1-bgo.left;}");
                    script.AppendLine("$(\"#\"+fid).css({\"position\": \"fixed\",\"display\":\"inline-grid\",\"top\":top+'px',\"left\":left+'px'});");
                    script.AppendLine("})");
                }
                #endregion
            }
            #region 多语公共js
            if (formFields.Exists(f => f.CurrentColumn.IsMultiLang == 1))
            {
                //关闭按钮事件
                script.AppendLine(" $(\".multilangpopoverclose\").on(ace.click_event, function () {     $(this).closest(\".popover\").css(\"display\",\"none\");  });");
                script.AppendLine(@"function multiLangPoverClose() {" +
                                  @"$('.popovermultilang').css('display','none');" +
                                  "document.removeEventListener(\"mousedown\", onMultiLangPoverMouseDown, false);}" +
                                  "function onMultiLangPoverMouseDown(event) {" +
                                  "if (!(event.target.className.indexOf(\"popovermultilang\")>0 || $(event.target).parents(\".popovermultilang\").length > 0)) {" +
                                  "multiLangPoverClose();" +
                                  "}}");
            }
            #endregion

            #region TextArea
            if (hasTextArea)
            {
                script.AppendLine(@"$('textarea.limited').inputlimiter({
					remText: '%n 字符剩余...',
					limitText: '最大字符数 : %n.'
				});"                );
            }
            #endregion

            #region 表单校验

            if (needValidate)
            {
                //校验
                script.AppendLine("$('###formid##').validate({");
                script.AppendLine("		errorElement: 'div',");
                script.AppendLine("		errorClass: 'error',");
                script.AppendLine("		focusInvalid: false,");
                script.AppendLine("		ignore: \"\",");
                script.AppendLine("		rules: {");
                foreach (FapColumn col in _fapColumns)
                {
                    //非空可见
                    if ((col.NullAble == 0 && col.ShowAble == 1) || col.RemoteChkURL.IsPresent())
                    {
                        if (col.CtrlType == FapColumn.CTRL_TYPE_REFERENCE)
                        {
                            script.AppendLine("                " + col.ColName + "MC" + ": {");
                        }
                        else
                        {
                            script.AppendLine("             " + col.ColName + ": {");
                        }
                        if (col.NullAble == 0 && col.ShowAble == 1)
                        {
                            script.AppendLine("				required: true,");
                        }
                        if (col.RemoteChkURL.IsPresent())
                        {
                            string oriValue = FormData.Get(col.ColName).ToString();
                            script.AppendLine("				remote: '"+ _applicationContext.BaseUrl + col.RemoteChkURL + "&fid=" + HttpUtility.UrlEncode(FidValue) + "&orivalue=" + HttpUtility.UrlEncode(oriValue) + "&currcol=" + HttpUtility.UrlEncode(col.ColName) + "',");
                        }
                        script.AppendLine("			},");
                    }
                }


                script.AppendLine("			},");

                script.AppendLine("		messages: {");

                foreach (FapColumn col in _fapColumns)
                {
                    //非空可见
                    if ((col.NullAble == 0 && col.ShowAble == 1) || col.RemoteChkURL.IsPresent())
                    {
                        if (col.CtrlType == FapColumn.CTRL_TYPE_REFERENCE)
                        {
                            script.AppendLine("                " + col.ColName + "MC" + ": {");
                        }
                        else
                        {
                            script.AppendLine("                " + col.ColName + ": {");
                        }
                        if (col.NullAble == 0 && col.ShowAble == 1)
                        {
                            script.AppendLine("				required: \"["+ col.ColComment + "]必须填写!\",");
                        }
                        if (col.RemoteChkURL.IsPresent())
                        {
                            string msg = col.RemoteChkMsg;
                            if (msg.IsMissing())
                            {
                                msg = "[" + col.ColComment + "]此项值已经存在,请更换";
                            }
                            script.AppendLine("				remote: \""+ msg + "\",");
                        }
                        script.AppendLine("			},");
                    }
                }
                script.AppendLine("		},");
                //校验容器
                script.AppendLine("errorLabelContainer: $(\"###formid## div.error\"),");
                script.AppendLine("		highlight: function (e) {");
                script.AppendLine("			$(e).closest('.form-group').removeClass('has-info').addClass('has-error');");
                script.AppendLine("		},");

                script.AppendLine("		success: function (e) {");
                script.AppendLine("			$(e).closest('.form-group').removeClass('has-error');//.addClass('has-info');");
                script.AppendLine("			$(e).remove();");
                script.AppendLine("		},");

                script.AppendLine("		errorPlacement: function (error, element) {");
                script.AppendLine("			if(element.is('input[type=checkbox]') || element.is('input[type=radio]')) {");
                script.AppendLine("				var controls = element.closest('div[class*=\"col-\"]');");
                script.AppendLine("				if(controls.find(':checkbox,:radio').length > 1) controls.append(error);");
                script.AppendLine("				else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));");
                script.AppendLine("			}");
                //script.AppendLine("			else if(element.is('.select2')) {");
                //script.AppendLine("				error.insertAfter(element.siblings('[class*=\"select2-container\"]:eq(0)'));");
                //script.AppendLine("			}");
                script.AppendLine("			else if(element.is('.chosen-select')) {");
                script.AppendLine("				error.insertAfter(element.siblings('[class*=\"chosen-container\"]:eq(0)'));");
                script.AppendLine("			}");
                script.AppendLine("			else error.insertAfter(element.parent());");
                script.AppendLine("		},");

                script.AppendLine("		submitHandler: function (form) {");
                script.AppendLine("		},");
                script.AppendLine("		invalidHandler: function (form) {");
                script.AppendLine("		}");
                script.AppendLine("	});");
            }
            #endregion

            #region 表单联动脚本
            DynamicParameters pm = new DynamicParameters();
            pm.Add("TableName", _fapTable.TableName);
            var formInjections = _dbContext.QueryWhere <FapFormInjection>("TableName=@TableName and IsEnabled=1", pm);
            if (formInjections != null && formInjections.Any())
            {
                foreach (var inject in formInjections)
                {
                    var changCol = _fapColumns.FirstOrDefault(f => f.ColName == inject.ChangeColumn);
                    //可见可编辑
                    if (changCol != null && changCol.EditAble == 1 && changCol.ShowAble == 1)
                    {
                        string ctrlName = changCol.ColName;

                        if (changCol.CtrlType == FapColumn.CTRL_TYPE_REFERENCE)
                        {
                            ctrlName = changCol.ColName + "MC";
                        }
                        script.AppendLine("$('#" + ctrlName + "').change(function(){");
                        string jsonData = "{'Fid':'" + inject.Fid + "','" + changCol.ColName + "':$('#" + changCol.ColName + "').val()";
                        if (inject.ParamColumns.IsPresent())
                        {
                            var paramCols = inject.ParamColumns.SplitComma();
                            foreach (var pc in paramCols)
                            {
                                jsonData += ",'" + pc + "':$('#" + pc + "').val()";
                            }
                        }
                        jsonData += "}";
                        script.AppendLine("$.post(basePath+'/Api/Core/frminjection'," + jsonData + ",function(result){");
                        script.AppendLine("$.each(result,function(name,value) {");
                        script.AppendLine("$('#'+name).val(value)");
                        script.AppendLine("});");
                        script.AppendLine("});");
                        script.AppendLine("})");
                    }
                }
            }

            #endregion

            #region 注入script脚本
            //元数据表注入
            if (_fapTable.ScriptInjection.IsPresent())
            {
                script.AppendLine(_fapTable.ScriptInjection);
            }
            //js文件注入
            string jsfilePath = Path.Combine(new string[] { Directory.GetCurrentDirectory(), "wwwroot", "Scripts", "FapFormPlugin", $"frm.plugin.{_fapTable.TableName}.js" });
            if (File.Exists(jsfilePath))
            {
                script.AppendLine(File.ReadAllText(jsfilePath, Encoding.UTF8));
            }
            #endregion

            script.AppendLine(" });");
            return(script.ToString());
        }
 public override void AddData(FormData data)
 {
     if (Name != null)
         data.Add(Name, Value);
 }
Exemplo n.º 41
0
        public async Task <IActionResult> UploadDatabase()
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                ModelState.AddModelError("File",
                                         $"The request couldn't be processed (Error 1).");
                // Log error

                return(BadRequest(ModelState));
            }

            // Accumulate the form data key-value pairs in the request (formAccumulator).
            var formAccumulator               = new KeyValueAccumulator();
            var trustedFileNameForDisplay     = string.Empty;
            var untrustedFileNameForStorage   = string.Empty;
            var trustedFilePathStorage        = string.Empty;
            var trustedFileNameForFileStorage = string.Empty;
            var streamedFileContent           = new byte[0];
            var streamedFilePhysicalContent   = new byte[0];

            // List Byte for file storage
            List <byte[]> filesByteStorage         = new List <byte[]>();
            List <string> filesNameStorage         = new List <string>();
            var           fileStoredData           = new Dictionary <string, byte[]>();
            List <string> storedPaths              = new List <string>();
            List <string> storedPathDictionaryKeys = new List <string>();

            // List to Submit
            List <ClamSectionAcademicSubCategoryItem> itemList = new List <ClamSectionAcademicSubCategoryItem>();

            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, HttpContext.Request.Body);

            var section = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                var hasContentDispositionHeader =
                    ContentDispositionHeaderValue.TryParse(
                        section.ContentDisposition, out var contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper
                        .HasFileContentDisposition(contentDisposition))
                    {
                        untrustedFileNameForStorage = contentDisposition.FileName.Value;
                        // Don't trust the file name sent by the client. To display
                        // the file name, HTML-encode the value.
                        trustedFileNameForDisplay = WebUtility.HtmlEncode(
                            contentDisposition.FileName.Value);

                        if (!Directory.Exists(_targetFilePath))
                        {
                            string path = String.Format("{0}", _targetFilePath);
                            Directory.CreateDirectory(path);
                        }

                        //streamedFileContent =
                        //    await FileHelpers.ProcessStreamedFile(section, contentDisposition,
                        //        ModelState, _permittedExtentions, _fileSizeLimit);

                        streamedFilePhysicalContent = await FileHelpers.ProcessStreamedFile(
                            section, contentDisposition, ModelState,
                            _permittedExtentions, _fileSizeLimit);

                        filesNameStorage.Add(trustedFileNameForDisplay);
                        filesByteStorage.Add(streamedFilePhysicalContent);
                        fileStoredData.Add(trustedFileNameForDisplay, streamedFilePhysicalContent);

                        if (!ModelState.IsValid)
                        {
                            return(BadRequest(ModelState));
                        }
                    }
                    else if (MultipartRequestHelper
                             .HasFormDataContentDisposition(contentDisposition))
                    {
                        // Don't limit the key name length because the
                        // multipart headers length limit is already in effect.
                        var key = HeaderUtilities
                                  .RemoveQuotes(contentDisposition.Name).Value;
                        var encoding = GetEncoding(section);

                        if (encoding == null)
                        {
                            ModelState.AddModelError("File",
                                                     $"The request couldn't be processed (Error 2).");
                            // Log error

                            return(BadRequest(ModelState));
                        }

                        using (var streamReader = new StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 1024,
                                   leaveOpen: true))
                        {
                            // The value length limit is enforced by
                            // MultipartBodyLengthLimit
                            var value = await streamReader.ReadToEndAsync();

                            if (string.Equals(value, "undefined",
                                              StringComparison.OrdinalIgnoreCase))
                            {
                                value = string.Empty;
                            }

                            formAccumulator.Append(key, value);

                            if (formAccumulator.ValueCount >
                                _defaultFormOptions.ValueCountLimit)
                            {
                                // Form key count limit of
                                // _defaultFormOptions.ValueCountLimit
                                // is exceeded.
                                ModelState.AddModelError("File",
                                                         $"The request couldn't be processed (Error 3).");
                                // Log error

                                return(BadRequest(ModelState));
                            }
                        }
                    }
                }

                // Drain any remaining section body that hasn't been consumed and
                // read the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            // Bind form data to the model
            var formData          = new FormData();
            var formValueProvider = new FormValueProvider(
                BindingSource.Form,
                new FormCollection(formAccumulator.GetResults()),
                CultureInfo.CurrentCulture);
            var bindingSuccessful = await TryUpdateModelAsync(formData, prefix : "",
                                                              valueProvider : formValueProvider);

            //trustedFilePathStorage = String.Format("{0}\\{1}\\{2}\\{3}",
            //    //_targetFilePath,
            //    _targetFolderPath,
            //    formData.AcademicId,
            //    formData.SubCategoryId,
            //    Path.GetRandomFileName());

            if (!bindingSuccessful)
            {
                ModelState.AddModelError("File",
                                         "The request couldn't be processed (Error 5).");
                // Log error

                return(BadRequest(ModelState));
            }

            // **WARNING!**
            // In the following example, the file is saved without
            // scanning the file's contents. In most production
            // scenarios, an anti-virus/anti-malware scanner API
            // is used on the file before making the file available
            // for download or for use by other systems.
            // For more information, see the topic that accompanies
            // this sample app.

            foreach (var item in fileStoredData)
            {
                trustedFilePathStorage = String.Format("{0}\\{1}\\{2}\\{3}",
                                                       _targetFolderPath,
                                                       formData.AcademicId,
                                                       formData.SubCategoryId,
                                                       Path.GetRandomFileName());
                Directory.CreateDirectory(trustedFilePathStorage);

                using (var targetStream = System.IO.File.Create(
                           Path.Combine(trustedFilePathStorage, item.Key)))
                {
                    await targetStream.WriteAsync(item.Value);

                    _logger.LogInformation(
                        "Uploaded file '{TrustedFileNameForDisplay}' saved to " +
                        "'{TargetFilePath}' as {TrustedFileNameForFileStorage}",
                        item.Key, trustedFilePathStorage,
                        item.Key);
                }

                itemList.Add(new ClamSectionAcademicSubCategoryItem()
                {
                    ItemPath  = Path.Combine(trustedFilePathStorage, item.Key),
                    ItemTitle = item.Key,
                    //ItemDescription = formData.Note,
                    Size          = item.Value.Length,
                    DateAdded     = DateTime.Now,
                    SubCategoryId = formData.SubCategoryId,
                    AcademicId    = formData.AcademicId
                });
            }


            //using (var targetStream = System.IO.File.Create(
            //                Path.Combine(trustedFilePathStorage, trustedFileNameForDisplay)))
            //{
            //    await targetStream.WriteAsync(streamedFilePhysicalContent);

            //    _logger.LogInformation(
            //        "Uploaded file '{TrustedFileNameForDisplay}' saved to " +
            //        "'{TargetFilePath}' as {TrustedFileNameForFileStorage}",
            //        trustedFileNameForDisplay, trustedFilePathStorage,
            //        trustedFileNameForDisplay);
            //}

            //var file = new ClamSectionAcademicSubCategoryItem()
            //{
            //    ItemPath = Path.Combine(trustedFilePathStorage, trustedFileNameForDisplay),
            //    ItemTitle = untrustedFileNameForStorage,
            //    //ItemDescription = formData.Note,
            //    Size = streamedFilePhysicalContent.Length,
            //    DateAdded = DateTime.Now,
            //    SubCategoryId = formData.SubCategoryId,
            //    AcademicId = formData.AcademicId
            //};

            await _context.AddRangeAsync(itemList);

            await _context.SaveChangesAsync();

            return(RedirectToAction("Episode", "Academia", new { id = formData.AcademicId, said = formData.SubCategoryId }));
        }
Exemplo n.º 42
0
 internal override void Apply(FormData formData)
     => formData.GetField(FieldName).Value = Value;
Exemplo n.º 43
0
        private RequestBody ConvertBody(PST.Body body)
        {
            if (body == null)
            {
                return(new RequestBody());
            }

            var result = new RequestBody();

            if (body.Mode == "raw")
            {
                // Set raw body text
                switch (body.Options?.Raw?.Language)
                {
                case "json":
                    result.JsonBody = body.Raw;
                    result.BodyType = RequestBodyType.Json;
                    break;

                case "xml":
                    result.XmlBody  = body.Raw;
                    result.BodyType = RequestBodyType.Xml;
                    break;

                default:
                    result.TextBody = body.Raw;
                    result.BodyType = RequestBodyType.Text;
                    break;
                }
            }
            else if (body.Mode == "urlencoded" && body.Urlencoded != null)
            {
                result.BodyType = RequestBodyType.FormEncoded;

                foreach (var postmanUrlEncoded in body.Urlencoded)
                {
                    var parameter = new Parameter
                    {
                        Type  = ParamType.FormEncodedData,
                        Key   = postmanUrlEncoded.Key,
                        Value = postmanUrlEncoded.Value
                    };

                    result.FormEncodedData?.Add(parameter);
                }
            }
            else if (body.Mode == "formdata" && body.Formdata != null)
            {
                result.BodyType = RequestBodyType.FormData;

                foreach (var postmanForm in body.Formdata)
                {
                    var nightingaleForm = new FormData
                    {
                        ContentType = postmanForm.ContentType,
                        Key         = postmanForm.Key,
                        Value       = postmanForm.Value,
                        FilePaths   = new List <string>(),
                        Enabled     = !postmanForm.Disabled
                    };

                    if (postmanForm.Type == "text")
                    {
                        nightingaleForm.FormDataType = FormDataType.Text;
                    }
                    else if (postmanForm.Type == "file")
                    {
                        nightingaleForm.FormDataType = FormDataType.File;
                    }

                    if (postmanForm.Src is string[] src)
                    {
                        foreach (var s in src)
                        {
                            if (string.IsNullOrWhiteSpace(s))
                            {
                                continue;
                            }

                            nightingaleForm.FilePaths.Add(s.TrimStart('/'));
                        }
                    }

                    result.FormDataList?.Add(nightingaleForm);
                }
            }
            else if (body.Mode == "file" && body.File?.Src != null)
            {
                result.BinaryFilePath = body.File.Src.TrimStart('/');
                result.BodyType       = RequestBodyType.Binary;
            }

            return(result);
        }
Exemplo n.º 44
0
        private async Task LoadingPageDataAllAsync()
        {
            await Task.Run(() => FormData.AssembliesPLFForm(Page, User.Identity.Name, schoolYear, schoolCode));

            //  await Task.Run(() => FormData.AssembliesPLFForm(Page, User.Identity.Name, WorkingProfile.SchoolYear, WorkingProfile.SchoolCode));
        }
Exemplo n.º 45
0
 public ApiResult <FormData> PostFormData(FormData formData)
 {
     return(GetApiResult(formData));
 }
Exemplo n.º 46
0
 private void handleFormDataChanges(FormData obj)
 {
     CurrentData.Data = (FormData)obj.Clone();
 }
Exemplo n.º 47
0
        public IActionResult Index()
        {
            var model = new FormData();

            return(View(model));
        }
Exemplo n.º 48
0
 public FrmAnnotation(FormData fd)
 {
     this._fd = fd;
     InitializeComponent();
 }
        public void SaveExecuted(object param)
        {
            int i = dbOperations.QueryEphemerisList().Count;

            //var counter = dbOperations.QueryEphemerisNamesList().Count;
            _formData             = new FormData();
            _formData.MonitorBody = SelectedBody;


            DateTime      dzero = new DateTime(1, 1, 1);
            StringBuilder buf   = new StringBuilder();

            _formData.swisseph(buf);


            List <TableEphemerisEntry> calculatedEntries = new List <TableEphemerisEntry>();

            //DateTime from = new DateTime(int.Parse(EDIT_FROM_YEAR.Text), int.Parse(EDIT_FROM_MONTH.Text), int.Parse(EDIT_FROM_DAY.Text));
            //DateTime until = new DateTime(int.Parse(EDIT_UNTIL_YEAR.Text), int.Parse(EDIT_UNTIL_MONTH.Text), int.Parse(EDIT_UNTIL_DAY.Text));

            //int interval = int.Parse(textBox1.Text);

            //Crude_Entries ce = new Crude_Entries
            //{
            //    ce_id = Guid.NewGuid(),
            //    ce_ephemerisname = EDIT_OBJECT.Text,
            //    ce_from = from,
            //    ce_until = until,
            //    ce_geomatricallatitude = "GeoLat",
            //    ce_geometricallongitude = "GeoLon",
            //    ce_system = "LeSystem",
            //    ce_withasteroids = new byte[] { 1 },
            //    ce_withhyperbolicbodies = new byte[] { 0 },
            //    ce_service = "LeService",
            //    ce_object = "Sun",
            //    ce_abovesea = 399,
            //    ce_intervals = "intervals"
            //};

            if (SelectedIntervalString.Equals("Days"))
            {
                //Days
                while ((DateTimeFrom - dzero).TotalDays < (DateTimeUntil - dzero).TotalDays)
                {
                    _formData.DateTime = DateTimeFrom;
                    _formData.swisseph(buf);
                    calculatedEntries.Add(_formData.ExtractTemplateFromStringBuilder());

                    DateTimeFrom = DateTimeFrom.AddDays(SelectedInterval);
                }
            }
            else if (SelectedIntervalString.Equals("Months"))
            {
                //    //Months
                while (MonthDifference(DateTimeUntil, DateTimeFrom) > 0)
                {
                    _formData.DateTime = DateTimeFrom;
                    _formData.swisseph(buf);
                    calculatedEntries.Add(_formData.ExtractTemplateFromStringBuilder());

                    DateTimeFrom = DateTimeFrom.AddMonths(SelectedInterval);
                }
            }
            else if (SelectedIntervalString.Equals("Years"))
            {
                //    //Years
                while (YearDifference(DateTimeUntil, DateTimeFrom) > 0)
                {
                    _formData.DateTime = DateTimeFrom;
                    _formData.swisseph(buf);
                    calculatedEntries.Add(_formData.ExtractTemplateFromStringBuilder());

                    DateTimeFrom = DateTimeFrom.AddYears(SelectedInterval);
                }
            }


            ////MessageBox.Show(calculatedEntries.Count.ToString(), "asdf");

            //Crude_Entries crude = CreateNewCrudeEntries();

            //insertCrudeEntry(crude);
            //CreateTable(crude.ce_id);

            //InsertObjectIntoTable(crude.ce_id, calculatedEntries);

            //MessageBox.Show("Done", "ai");
        }
Exemplo n.º 50
0
 public CallableAnonymousInnerClass(AbstractGetDeployedFormCmd outerInstance, CommandContext commandContext, FormData formData, string resourceName)
 {
     this.outerInstance  = outerInstance;
     this.commandContext = commandContext;
     this.formData       = formData;
     this.resourceName   = resourceName;
 }
Exemplo n.º 51
0
        //[DisableFormValueModelBinding]
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> UploadDatabase()
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                ModelState.AddModelError("File",
                                         $"The request couldn't be processed (Error 1).");
                // Log error

                return(BadRequest(ModelState));
            }

            // Accumulate the form data key-value pairs in the request (formAccumulator).
            var formAccumulator             = new KeyValueAccumulator();
            var trustedFileNameForDisplay   = string.Empty;
            var untrustedFileNameForStorage = string.Empty;
            var streamedFileContent         = new byte[0];

            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, HttpContext.Request.Body);

            var section = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                var hasContentDispositionHeader =
                    ContentDispositionHeaderValue.TryParse(
                        section.ContentDisposition, out var contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper
                        .HasFileContentDisposition(contentDisposition))
                    {
                        untrustedFileNameForStorage = contentDisposition.FileName.Value;
                        // Don't trust the file name sent by the client. To display
                        // the file name, HTML-encode the value.
                        trustedFileNameForDisplay = WebUtility.HtmlEncode(
                            contentDisposition.FileName.Value);

                        streamedFileContent =
                            await FilesOptionHelper.ProcessStreamedFile(section, contentDisposition,
                                                                        ModelState, _permittedExtensions, _fileSizeLimit);

                        if (!ModelState.IsValid)
                        {
                            return(BadRequest(ModelState));
                        }
                    }
                    else if (MultipartRequestHelper
                             .HasFormDataContentDisposition(contentDisposition))
                    {
                        // Don't limit the key name length because the
                        // multipart headers length limit is already in effect.
                        var key = HeaderUtilities
                                  .RemoveQuotes(contentDisposition.Name).Value;
                        var encoding = GetEncoding(section);

                        if (encoding == null)
                        {
                            ModelState.AddModelError("File",
                                                     $"The request couldn't be processed (Error 2).");
                            // Log error

                            return(BadRequest(ModelState));
                        }

                        using (var streamReader = new StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 1024,
                                   leaveOpen: true))
                        {
                            // The value length limit is enforced by
                            // MultipartBodyLengthLimit
                            var value = await streamReader.ReadToEndAsync();

                            if (string.Equals(value, "undefined",
                                              StringComparison.OrdinalIgnoreCase))
                            {
                                value = string.Empty;
                            }

                            formAccumulator.Append(key, value);

                            if (formAccumulator.ValueCount >
                                _defaultFormOptions.ValueCountLimit)
                            {
                                // Form key count limit of
                                // _defaultFormOptions.ValueCountLimit
                                // is exceeded.
                                ModelState.AddModelError("File",
                                                         $"The request couldn't be processed (Error 3).");
                                // Log error

                                return(BadRequest(ModelState));
                            }
                        }
                    }
                }

                // Drain any remaining section body that hasn't been consumed and
                // read the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            // Bind form data to the model
            var formData          = new FormData();
            var formValueProvider = new FormValueProvider(
                BindingSource.Form,
                new FormCollection(formAccumulator.GetResults()),
                CultureInfo.CurrentCulture);
            var bindingSuccessful = await TryUpdateModelAsync(formData, prefix : "",
                                                              valueProvider : formValueProvider);

            if (!bindingSuccessful)
            {
                ModelState.AddModelError("File",
                                         "The request couldn't be processed (Error 5).");
                // Log error

                return(BadRequest(ModelState));
            }

            // **WARNING!**
            // In the following example, the file is saved without
            // scanning the file's contents. In most production
            // scenarios, an anti-virus/anti-malware scanner API
            // is used on the file before making the file available
            // for download or for use by other systems.
            // For more information, see the topic that accompanies
            // this sample app.

            var file = new AppFile()
            {
                Content       = streamedFileContent,
                UntrustedName = untrustedFileNameForStorage,
                Note          = formData.Note,
                Size          = streamedFileContent.Length,
                UploadDT      = DateTime.UtcNow
            };

            _context.Files.Add(file);
            await _context.SaveChangesAsync();

            return(Created(nameof(SampleController), null));
        }
Exemplo n.º 52
0
        //Fill listboxes.
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            int role = Convert.ToInt32(_proxy.GetItemProperty(user, EngServRef.ServerData.User, EngServRef.PropertyData.Role));

            if (name != null)
            {
                txtName.Text = name;
            }

            if (editForm)
            {
                string plural = _proxy.GetItemProperty(wordsId, EngServRef.ServerData.Word, EngServRef.PropertyData.PluralForm);
                string past   = _proxy.GetItemProperty(wordsId, EngServRef.ServerData.Word, EngServRef.PropertyData.PastForm);
                string pastTh = _proxy.GetItemProperty(wordsId, EngServRef.ServerData.Word, EngServRef.PropertyData.PastThForm);
                if (plural != null)
                {
                    grForm.Visibility   = Visibility.Visible;
                    stPlural.Visibility = Visibility.Visible;
                    txtPlural.Text      = plural;
                }
                if (past != null)
                {
                    grForm.Visibility = Visibility.Visible;
                    stPast.Visibility = Visibility.Visible;
                    txtPast.Text      = past;
                }
                if (pastTh != null)
                {
                    grForm.Visibility           = Visibility.Visible;
                    stPastParticiple.Visibility = Visibility.Visible;
                    txtPastTh.Text = pastTh;
                }
                int tran = Convert.ToInt32(_proxy.GetItemProperty(wordsId, EngServRef.ServerData.Word, EngServRef.PropertyData.Transcription));
                if (tran != 0)
                {
                    txtAmerican.Text   = _proxy.GetItemProperty(tran, EngServRef.ServerData.Transcription, EngServRef.PropertyData.American);
                    txtBritish.Text    = _proxy.GetItemProperty(tran, EngServRef.ServerData.Transcription, EngServRef.PropertyData.British);
                    txtCanadian.Text   = _proxy.GetItemProperty(tran, EngServRef.ServerData.Transcription, EngServRef.PropertyData.Canadian);
                    txtAustralian.Text = _proxy.GetItemProperty(tran, EngServRef.ServerData.Transcription, EngServRef.PropertyData.Australian);
                }
                string imgPath = _proxy.GetItemProperty(wordsId, EngServRef.ServerData.Word, EngServRef.PropertyData.Imgpath);
                if (imgPath != null)
                {
                    if (File.Exists($@"Temp\WordImages\{imgPath}"))
                    {
                        FormData.SetImage($@"pack://siteoforigin:,,,/Temp\WordImages\{imgPath}", imDrag);
                    }
                }
                FillExamples(new List <int>(_proxy.GetItemData(wordsId, EngServRef.ServerData.Word, EngServRef.ServerData.Example)));
                FillDefinitions(new List <int>(_proxy.GetItemData(wordsId, EngServRef.ServerData.Word, EngServRef.ServerData.Definition)));
                FillTranslations(new List <int>(_proxy.GetItemData(wordsId, EngServRef.ServerData.Word, EngServRef.ServerData.Translation)));
            }
            if (_proxy.GetItemProperty(role, EngServRef.ServerData.Role, EngServRef.PropertyData.Name) == "admin")
            {
                if (!editForm)
                {
                    FillGroups();
                }
                else
                {
                    List <int> groups = new List <int>(_proxy.GetItemData(wordsId, EngServRef.ServerData.Word, EngServRef.ServerData.Group));
                    FillGroups(groups);
                }
                stGroups.Visibility = Visibility.Visible;
            }
            if (!editForm)
            {
                FillCategories();
            }
            else
            {
                List <int> categories = new List <int>(_proxy.GetItemData(wordsId, EngServRef.ServerData.Word, EngServRef.ServerData.WordCategory));
                FillCategories(categories);
            }
        }
        public IFlowUiDefinition GetCurrentUiDefinition(FlowToken flowToken)
        {
            WorkflowFlowToken workflowFlowToken = (WorkflowFlowToken)flowToken;

            if (!WorkflowFacade.WorkflowExists(workflowFlowToken.WorkflowInstanceId))
            {
                Log.LogVerbose(LogTitle, "The workflow with Id = {0} does not exists", workflowFlowToken.WorkflowInstanceId);
                return(null);
            }


            using (GlobalInitializerFacade.CoreNotLockedScope)
            {
                Semaphore semaphore = WorkflowFacade.WaitForIdleStatus(workflowFlowToken.WorkflowInstanceId);
                if (semaphore != null)
                {
                    Log.LogVerbose(LogTitle, "The workflow with Id = {0} is running, waiting until its done.", workflowFlowToken.WorkflowInstanceId);

                    semaphore.WaitOne(TimeSpan.FromSeconds(10), true);

                    Log.LogVerbose(LogTitle, "Done waiting on the workflow with Id = {0}.", workflowFlowToken.WorkflowInstanceId);
                }
            }


            FormData formFunction = WorkflowFacade.GetFormData(workflowFlowToken.WorkflowInstanceId);

            if (formFunction == null)
            {
                return(null);
            }

            FormFlowUiDefinition formFlowUiDefinition;

            if (formFunction.FormDefinition != null)
            {
                formFlowUiDefinition = new FormFlowUiDefinition(
                    ToXmlReader(formFunction.FormDefinition),
                    formFunction.ContainerType,
                    formFunction.ContainerLabel,
                    formFunction.Bindings,
                    formFunction.BindingsValidationRules
                    );
            }
            else if (formFunction.FormMarkupProvider != null)
            {
                formFlowUiDefinition = new FormFlowUiDefinition(
                    formFunction.FormMarkupProvider,
                    formFunction.ContainerType,
                    formFunction.ContainerLabel,
                    formFunction.Bindings,
                    formFunction.BindingsValidationRules
                    );
            }
            else
            {
                throw new NotImplementedException();
            }

            var markup = GetCustomToolbarMarkup(formFunction);

            if (markup != null)
            {
                formFlowUiDefinition.SetCustomToolbarMarkupProvider(markup);
            }

            AddEventHandles(formFlowUiDefinition, workflowFlowToken.WorkflowInstanceId);

            return(formFlowUiDefinition);
        }
        private static void AddEventHandles(FormFlowUiDefinition formFlowUiDefinition, Guid instanceId)
        {
            IEnumerable <string> eventNames = WorkflowFacade.GetCurrentFormEvents(instanceId);

            FormData formData = WorkflowFacade.GetFormData(instanceId);

            foreach (string eventName in eventNames)
            {
                if (formData?.ExcludedEvents != null && formData.ExcludedEvents.Contains(eventName))
                {
                    continue;
                }

                switch (eventName)
                {
                case "Save":
                    formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.Save, OnSave);
                    break;

                case "SaveAndPublish":
                    formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.SaveAndPublish, OnSaveAndPublish);
                    break;

                case "Next":
                    formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.Next, OnNext);
                    break;

                case "Previous":
                    formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.Previous, OnPrevious);
                    break;

                case "Finish":
                    formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.Finish, OnFinish);
                    break;

                case "Cancel":
                    formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.Cancel, OnCancel);
                    break;

                case "Preview":
                    formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.Preview, OnPreview);
                    break;

                case "CustomEvent01":
                    formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.CustomEvent01, OnCustomEvent01);
                    break;

                case "CustomEvent02":
                    formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.CustomEvent02, OnCustomEvent02);
                    break;

                case "CustomEvent03":
                    formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.CustomEvent03, OnCustomEvent03);
                    break;

                case "CustomEvent04":
                    formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.CustomEvent04, OnCustomEvent04);
                    break;

                case "CustomEvent05":
                    formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.CustomEvent05, OnCustomEvent05);
                    break;
                }
            }

            IEventHandleFilter eventHandlerFilter = WorkflowFacade.GetEventHandleFilter(instanceId);

            eventHandlerFilter?.Filter(formFlowUiDefinition.EventHandlers);
        }
Exemplo n.º 55
0
        protected virtual void ApplyFormData(HttpRequest request)
        {
            if (FormData.Empty())
            {
                return;
            }

            if (request.ContentData != null)
            {
                throw new ApplicationException("Cannot send HttpRequest Body and FormData simultaneously.");
            }

            var shouldSendAsMultipart = FormData.Any(v => v.ContentType != null || v.FileName != null || v.ContentData.Length > 1024);

            if (shouldSendAsMultipart)
            {
                var boundary     = "-----------------------------" + DateTime.Now.Ticks.ToString("x14");
                var partBoundary = string.Format("--{0}\r\n", boundary);
                var endBoundary  = string.Format("--{0}--\r\n", boundary);

                var bodyStream = new MemoryStream();
                var summary    = new StringBuilder();

                using (var writer = new StreamWriter(bodyStream, new UTF8Encoding(false)))
                {
                    foreach (var formData in FormData)
                    {
                        writer.Write(partBoundary);

                        writer.Write("Content-Disposition: form-data");
                        if (formData.Name.IsNotNullOrWhiteSpace())
                        {
                            writer.Write("; name=\"{0}\"", formData.Name);
                        }
                        if (formData.FileName.IsNotNullOrWhiteSpace())
                        {
                            writer.Write("; filename=\"{0}\"", formData.FileName);
                        }
                        writer.Write("\r\n");

                        if (formData.ContentType.IsNotNullOrWhiteSpace())
                        {
                            writer.Write("Content-Type: {0}\r\n", formData.ContentType);
                        }

                        writer.Write("\r\n");
                        writer.Flush();

                        bodyStream.Write(formData.ContentData, 0, formData.ContentData.Length);
                        writer.Write("\r\n");

                        if (formData.FileName.IsNotNullOrWhiteSpace())
                        {
                            summary.AppendFormat("\r\n{0}={1} ({2} bytes)", formData.Name, formData.FileName, formData.ContentData.Length);
                        }
                        else
                        {
                            summary.AppendFormat("\r\n{0}={1}", formData.Name, Encoding.UTF8.GetString(formData.ContentData));
                        }
                    }

                    writer.Write(endBoundary);
                }

                var body = bodyStream.ToArray();

                // TODO: Scan through body to see if we have a boundary collision?

                request.Headers.ContentType = "multipart/form-data; boundary=" + boundary;
                request.SetContent(body);

                if (request.ContentSummary == null)
                {
                    request.ContentSummary = summary.ToString();
                }
            }
            else
            {
                var parameters = FormData.Select(v => string.Format("{0}={1}", v.Name, Uri.EscapeDataString(Encoding.UTF8.GetString(v.ContentData))));
                var urlencoded = string.Join("&", parameters);
                var body       = Encoding.UTF8.GetBytes(urlencoded);

                request.Headers.ContentType = "application/x-www-form-urlencoded";
                request.SetContent(body);

                if (request.ContentSummary == null)
                {
                    request.ContentSummary = urlencoded;
                }
            }
        }
Exemplo n.º 56
0
        public ActionResult DecodeText(FormData formData, FormCollection form)
        {
            SelectList items = new SelectList(ciphers);

            ViewBag.Ciphers = items;
            // Caesar cipher decode
            if (Request.Form["Ciphers"] == "Caesar cipher")
            {
                if (formData.DecodedText != "")
                {
                    formData.DecodedText = "";
                }
                try
                {
                    int    temp = 0;
                    char[] text = formData.EncodedText.ToCharArray();
                    for (int i = 0; i < text.Length; i++)
                    {
                        for (int j = 0; j <= alphabet.Length; j++)
                        {
                            if (text[i].ToString() == alphabet[j].ToString())
                            {
                                temp = j - Convert.ToInt32(formData.tbkey);

                                if (temp < 0)
                                {
                                    temp += alphabet.Length;
                                }
                                if (temp >= alphabet.Length)
                                {
                                    temp -= alphabet.Length;
                                }

                                formData.DecodedText += alphabet[temp];
                                break;
                            }
                            continue;
                        }
                    }
                }
                catch (Exception ex)
                {
                    ViewBag.Exception = ex.Message;
                }
            }

            //  Vigenere cipher decode
            if (Request.Form["Ciphers"] == "Vigenere cipher")
            {
                if (formData.DecodedText != "")
                {
                    formData.DecodedText = "";
                }
                char[] text = formData.EncodedText.ToCharArray().Where(s => !char.IsWhiteSpace(s)).ToArray();
                char[] key  = formData.tbkey.ToCharArray();
                try
                {
                    char[,] Vigenere_Table = new char[26, 26];

                    int temp = 0;
                    for (int i = 0; i < alphabet.Length; i++)
                    {
                        for (int j = 0; j < 26; j++)
                        {
                            temp = j + i;
                            if (temp >= 26)
                            {
                                temp = temp % 26;
                            }
                            Vigenere_Table[i, j] = alphabet[temp];
                        }
                    }
                    // DECRYPT VIGENERE
                    for (int t = 0, k = 0; t < text.Length || k < key.Length; t++, k++)
                    {
                        if (t >= text.Length)
                        {
                            break;
                        }
                        if (k == key.Length)
                        {
                            k = 0;
                            for (int y = 0; y <= alphabet.Length; y++)
                            {
                                if (key[k].ToString() == alphabet[y].ToString())
                                {
                                    Xkey = y;
                                    for (int x = 0; x <= alphabet.Length; x++)
                                    {
                                        Ytext = x;
                                        if (Vigenere_Table[Ytext, Xkey].ToString() == text[t].ToString())
                                        {
                                            formData.DecodedText += alphabet[x].ToString();
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                        else
                        {
                            for (int y = 0; y <= alphabet.Length; y++)
                            {
                                if (key[k].ToString() == alphabet[y].ToString())
                                {
                                    Xkey = y;
                                    for (int x = 0; x <= alphabet.Length; x++)
                                    {
                                        Ytext = x;
                                        if (Vigenere_Table[Ytext, Xkey].ToString() == text[t].ToString())
                                        {
                                            formData.DecodedText += alphabet[x].ToString();
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    ViewBag.Exception = ex.Message;
                }
            }
            return(View(formData));
        }
Exemplo n.º 57
0
            private async Task <FormData> GetForm()
            {
                var formData = _environment.Get <FormData>("SuperGlue.Owin.Form#data");

                if (formData != null)
                {
                    return(formData);
                }

                var form = new Dictionary <string, List <string> >(StringComparer.OrdinalIgnoreCase);

                if (string.IsNullOrEmpty(Headers.ContentType))
                {
                    formData = new FormData(new ReadableStringCollection(form.ToDictionary(x => x.Key, x => x.Value.ToArray())), new List <HttpFile>());
                    Set("SuperGlue.Owin.Form#data", formData);
                    return(formData);
                }

                var contentType = Headers.ContentType;
                var mimeType    = contentType.Split(';').First();

                if (mimeType.Equals("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
                {
                    var reader = new StreamReader(Body, Encoding.UTF8, true, 4 * 1024, true);

                    var accumulator = new Dictionary <string, List <string> >(StringComparer.OrdinalIgnoreCase);

                    ParseDelimited(await reader.ReadToEndAsync().ConfigureAwait(false), new[] { '&' }, AppendItemCallback, accumulator);

                    foreach (var kv in accumulator)
                    {
                        form.Add(kv.Key, kv.Value);
                    }
                }

                if (!mimeType.Equals("multipart/form-data", StringComparison.OrdinalIgnoreCase))
                {
                    formData = new FormData(new ReadableStringCollection(form.ToDictionary(x => x.Key, x => x.Value.ToArray())), new List <HttpFile>());
                    Set("SuperGlue.Owin.Form#data", formData);
                    return(formData);
                }

                var boundary  = Regex.Match(contentType, @"boundary=(?<token>[^\n\; ]*)").Groups["token"].Value;
                var multipart = new HttpMultipart(Body, boundary);

                var files = new List <HttpFile>();

                foreach (var httpMultipartBoundary in multipart.GetBoundaries())
                {
                    if (string.IsNullOrEmpty(httpMultipartBoundary.Filename))
                    {
                        var reader = new StreamReader(httpMultipartBoundary.Value);

                        if (!form.ContainsKey(httpMultipartBoundary.Name))
                        {
                            form[httpMultipartBoundary.Name] = new List <string>();
                        }

                        form[httpMultipartBoundary.Name].Add(reader.ReadToEnd());
                    }
                    else
                    {
                        files.Add(new HttpFile(
                                      httpMultipartBoundary.ContentType,
                                      httpMultipartBoundary.Filename,
                                      httpMultipartBoundary.Value
                                      ));
                    }
                }

                formData = new FormData(new ReadableStringCollection(form.ToDictionary(x => x.Key, x => x.Value.ToArray())), files);
                Set("SuperGlue.Owin.Form#data", formData);
                return(formData);
            }
Exemplo n.º 58
0
 private void LoadingPageDataAll()
 {
     //  Loading_Title();
     //  Loading_Data();
     FormData.AssembliesPLFForm(Page, User.Identity.Name, schoolYear, schoolCode);
 }
        public void Form_Create_New_Blank()
        {
            Console.WriteLine("WindowHandle at Start: " + Driver.GetHashCode().ToString());

            var formData  = new FormData();
            var mainMenu  = new MainMenu(Driver);
            var formMenu  = new SubMenuForms(Driver);
            var formPages = new FormPages(Driver);

            var formWorkflow = new FormWorkflows(Driver, test);

            try  //Contains Contents of Test
            {
                //test.Log(LogStatus.Info, "Starting test at URL: " + BaseUrls["ApplitrackLoginPage"]);

                // navigate to Forms > Design Forms and Packets > Create New Form
                mainMenu.ClickForms();
                formMenu.ClickDesignFormsandPackets();
                formMenu.ClickCreateNewForm();
                test.Log(LogStatus.Pass, "Navigate to Forms > Design Forms and Packets > Create New Form");

                // click 'A blank form'
                Driver.SwitchToFrameById("MainContentsIFrame");
                formPages.CreateNewFormPage.ClickBlankForm();
                test.Log(LogStatus.Pass, "Click 'A blank form'");

                // enter form info
                Driver.SwitchToFrameById("tabs_Panel");
                formPages.EditAndCreateFormPage.PropertiesTab.ClickStandardFormRadioButton();
                test.Log(LogStatus.Pass, "Select the 'Standard Form' radio button");

                formPages.EditAndCreateFormPage.PropertiesTab.FillOutFormTitle(formData.FormTitle);
                test.Log(LogStatus.Pass, "Fill out the form title");

                // save
                Driver.SwitchToDefaultFrame();
                Driver.SwitchToFrameById("MainContentsIFrame");
                formPages.EditAndCreateFormPage.ClickSaveButton();
                test.Log(LogStatus.Pass, "Click the save button");
                var formId = formPages.EditAndCreateFormPage.GetFormId();
                Console.WriteLine("Form ID: {0}", formId);

                // verify that the form was created
                Driver.SwitchToDefaultFrame();
                mainMenu.ClickMainMenuTab();
                mainMenu.ClickForms();
                formMenu.ClickDesignFormsandPackets();
                formMenu.ClickEditForms();
                Driver.SwitchToFrameById("MainContentsIFrame");
                Assert.IsTrue(formPages.EditFormsPage.FormExists(formId));
                test.Log(LogStatus.Pass, "Verify the form exists");

                // delete the form
                formWorkflow.DeleteForm(formId);
                test.Log(LogStatus.Pass, "Delete the form");
            }
            catch (Exception e) //On Error Do
            {
                HandleException(e, Driver);
                throw;
            }
        }
Exemplo n.º 60
-1
        public static void PrintPreview(Window owner, FormData data)
        {
            using (MemoryStream xpsStream = new MemoryStream())
            {
                using (Package package = Package.Open(xpsStream, FileMode.Create, FileAccess.ReadWrite))
                {
                    string packageUriString = "memorystream://data.xps";
                    Uri packageUri = new Uri(packageUriString);

                    PackageStore.AddPackage(packageUri, package);

                    XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Maximum, packageUriString);
                    XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
                    Form visual = new Form(data);

                    PrintTicket printTicket = new PrintTicket();
                    printTicket.PageMediaSize = A4PaperSize;
                    writer.Write(visual, printTicket);
                    FixedDocumentSequence document = xpsDocument.GetFixedDocumentSequence();
                    xpsDocument.Close();

                    PrintPreviewWindow printPreviewWnd = new PrintPreviewWindow(document);
                    printPreviewWnd.Owner = owner;
                    printPreviewWnd.ShowDialog();
                    PackageStore.RemovePackage(packageUri);
                }
            }
        }