Example #1
0
        private static string GetHttpPage(string uri, HttpVerbOptions httpMethod, HttpDataTypeOptions httpDataType, string additionalHeadersText, string bodyRequest, string certificatePath = null, string privateKey = null)
        {
            Stream         dataStream = null;
            String         strResult;
            WebResponse    objResponse;
            HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(uri);

            if (certificatePath != null)
            {
                var bytes             = File.ReadAllBytes(certificatePath);
                X509Certificate2 cert = new X509Certificate2(bytes, privateKey);
                objRequest.ClientCertificates.Add(cert);
            }
            objRequest.Headers.Add(HttpRequestHeader.ContentEncoding, "gzip");
            SetAdditionalHeaders(objRequest, additionalHeadersText);

            objRequest.Method = httpMethod.ToString();

            // valore di default del content type
            objRequest.ContentType = "application/x-www-form-urlencoded";

            if (httpMethod == HttpVerbOptions.POST)
            {
                if (httpDataType == HttpDataTypeOptions.JSON)
                {
                    // JSON
                    objRequest.ContentType = "application/json; charset=utf-8";
                }

                // body del post
                byte[] buffer = System.Text.UTF8Encoding.UTF8.GetBytes(bodyRequest);
                dataStream = objRequest.GetRequestStream();
                dataStream.Write(buffer, 0, buffer.Length);
                dataStream.Close();
            }

            objRequest.PreAuthenticate = false;
            objResponse = objRequest.GetResponse();
            using (StreamReader sr = new StreamReader(objResponse.GetResponseStream())) {
                strResult = sr.ReadToEnd();
                sr.Close();
            }
            return(strResult);
        }
Example #2
0
        public dynamic GetContentfromField(Dictionary <string, object> contesto, string externalUrl, string nomexlst, FieldExternalSetting settings, string contentType = "", HttpVerbOptions httpMethod = HttpVerbOptions.GET, HttpDataTypeOptions httpDataType = HttpDataTypeOptions.JSON, string tokenizedAdditionalHeadersText = "", string bodyRequest = "")
        {
            dynamic ci       = null;
            string  UrlToGet = "";
            string  additionalHeadersText = "";
            string  prefix = _shellSetting.Name + "_";

            try {
                UrlToGet = GetUrl(contesto, externalUrl);
                additionalHeadersText = GetHeadersText(contesto, tokenizedAdditionalHeadersText);
                string chiavecache = UrlToGet;
                chiavecache = Path.GetInvalidFileNameChars().Aggregate(chiavecache, (current, c) => current.Replace(c.ToString(), string.Empty));
                chiavecache = chiavecache.Replace('&', '_');
                string chiavedate = prefix + "Date_" + chiavecache;
                chiavecache = prefix + chiavecache;
                dynamic ciDate = _cacheStorageProvider.Get <object>(chiavedate);
                if (settings.CacheMinute > 0)
                {
                    ci = _cacheStorageProvider.Get <object>(chiavecache);
                }
                if (ci == null || ciDate == null)
                {
                    string certPath;
                    string webpagecontent;
                    if (settings.CertificateRequired && !String.IsNullOrWhiteSpace(settings.CerticateFileName))
                    {
                        certPath = String.Format(HostingEnvironment.MapPath("~/") + @"App_Data\Sites\" + _shellSetting.Name + @"\ExternalFields\{0}", settings.CerticateFileName);
                        if (File.Exists(certPath))
                        {
                            webpagecontent = GetHttpPage(UrlToGet, httpMethod, httpDataType, additionalHeadersText, bodyRequest, certPath, settings.CertificatePrivateKey.DecryptString(_shellSetting.EncryptionKey)).Trim();
                        }
                        else
                        {
                            throw new Exception(String.Format("File \"{0}\" not found! Upload certificate via FTP.", certPath));
                        }
                    }
                    else
                    {
                        if (settings.DataType == OriginData.Executable)
                        {
                            string filename = HostingEnvironment.MapPath("~/") + @"App_Code\" + externalUrl.Substring(0, externalUrl.IndexOf(".exe") + 4);
                            if (!File.Exists(filename))
                            {
                                throw new Exception(String.Format("File \"{0}\" not found!", filename));
                            }
                            var tmptokenizedzedUrl = _tokenizer.Replace(externalUrl, contesto);

                            var StartInfo = new ProcessStartInfo {
                                FileName               = filename,
                                Arguments              = tmptokenizedzedUrl.Substring(tmptokenizedzedUrl.IndexOf(".exe") + 5),
                                UseShellExecute        = false,
                                RedirectStandardOutput = true,
                                RedirectStandardError  = true,
                                CreateNoWindow         = true,
                                StandardOutputEncoding = Encoding.UTF8
                            };
                            var versionInfo = FileVersionInfo.GetVersionInfo(filename);
                            if (versionInfo.CompanyName != "Laser Group")
                            {
                                throw new Exception(string.Format("ExternalExe {0}  has not correct CompanyName", filename));
                            }
                            else
                            {
                                using (var proc = Process.Start(StartInfo)) {
                                    webpagecontent = proc.StandardOutput.ReadToEnd();
                                    string err = proc.StandardError.ReadToEnd();
                                    if (!string.IsNullOrEmpty(err))
                                    {
                                        Logger.Error(string.Format("ExternalExe {0}  : {1}", externalUrl, err));
                                    }
                                    proc.WaitForExit();
                                };
                            }
                        }
                        else
                        {
                            webpagecontent = GetHttpPage(UrlToGet, httpMethod, httpDataType, additionalHeadersText, bodyRequest).Trim();
                        }
                    }
                    if (!webpagecontent.StartsWith("<"))
                    {
                        if (webpagecontent.StartsWith("["))
                        {
                            webpagecontent = String.Concat("{\"", nomexlst, "List", "\":", webpagecontent, "}");
                        }

                        if (webpagecontent.Trim() == "")
                        {
                            // fix json vuoto
                            webpagecontent = "{}";
                        }

                        JObject jsonObject    = JObject.Parse(webpagecontent);
                        JObject newJsonObject = new JObject();
                        newJsonObject  = jsonflusher(jsonObject);
                        webpagecontent = newJsonObject.ToString();
                        XmlDocument newdoc = new XmlDocument();
                        newdoc = JsonConvert.DeserializeXmlNode(webpagecontent, "root");
                        correggiXML(newdoc);
                        webpagecontent = newdoc.InnerXml;
                    }

                    // fix json vuoto
                    if (webpagecontent == "<root />")
                    {
                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.LoadXml(webpagecontent);

                        XmlNode xmlNode = xmlDoc.DocumentElement;
                        xmlNode = XmlWithJsonArrayTag(xmlNode, xmlDoc);

                        string JsonVuoto = JsonConvert.SerializeXmlNode(xmlNode);

                        JavaScriptSerializer ser = new JavaScriptSerializer()
                        {
                            MaxJsonLength = Int32.MaxValue
                        };
                        dynamic dynamiccontent_tmp = ser.Deserialize(JsonVuoto, typeof(object));
                        ci = new DynamicJsonObject(dynamiccontent_tmp as IDictionary <string, object>);
                    }
                    else
                    {
                        dynamic mycache = null;
                        Dictionary <string, object> dvb = new Dictionary <string, object>();
                        if (!string.IsNullOrEmpty(settings.CacheInput))
                        {
                            string inputcache = _tokenizer.Replace(settings.CacheInput, contesto);
                            mycache = _cacheStorageProvider.Get <object>(inputcache);
                            if (mycache == null)
                            {
                                if (File.Exists(String.Format(HostingEnvironment.MapPath("~/") + "App_Data/Cache/" + inputcache)))
                                {
                                    string filecontent = File.ReadAllText(String.Format(HostingEnvironment.MapPath("~/") + "App_Data/Cache/" + inputcache));
                                    mycache = JsonConvert.DeserializeObject(filecontent);
                                    _cacheStorageProvider.Put(inputcache, mycache);
                                }
                            }
                        }
                        if (mycache != null)
                        {
                            XmlDocument xml = JsonConvert.DeserializeXmlNode(JsonConvert.SerializeObject(mycache));
                            dvb.Add("CachedData", xml);
                        }
                        else
                        {
                            dvb.Add("CachedData", new XmlDocument());
                        }
                        dvb.Add("externalUrl", UrlToGet);
                        dvb.Add("OrchardServices", _orchardServices);
                        ci = RazorTransform(webpagecontent.Replace(" xmlns=\"\"", ""), nomexlst, contentType, dvb);

                        _cacheStorageProvider.Remove(chiavecache);
                        _cacheStorageProvider.Remove(chiavedate);
                        if (settings.CacheMinute > 0)
                        {
                            _cacheStorageProvider.Put(chiavecache, (object)ci);

                            // Use TimeSpan constructor to specify:
                            // ... Days, hours, minutes, seconds, milliseconds.
                            _cacheStorageProvider.Put(chiavedate, new { When = DateTime.UtcNow }, new TimeSpan(0, 0, settings.CacheMinute, 0, 0));
                        }
                        if (settings.CacheToFileSystem)
                        {
                            if (!Directory.Exists(HostingEnvironment.MapPath("~/") + "App_Data/Cache"))
                            {
                                Directory.CreateDirectory(HostingEnvironment.MapPath("~/") + "App_Data/Cache");
                            }
                            using (StreamWriter sw = File.CreateText(String.Format(HostingEnvironment.MapPath("~/") + "App_Data/Cache/" + chiavecache))) {
                                sw.WriteLine(JsonConvert.SerializeObject(ci));//, Jsettings));// new JsonSerializerSettings {  EmptyArrayHandling = EmptyArrayHandling.Set }));
                            }
                        }
                    }
                }
            }
            catch (Exception ex) {
                Logger.Error(ex, UrlToGet);
                throw new ExternalFieldRemoteException();
            }
            return(ci);
        }