public static bool HaveExternalIP()
        {
            if (!_haveExternalIP.HasValue)
            {
                string convertUri;
                try
                {
                    var uri = new UriBuilder(HttpContext.Current.Request.Url)
                    {
                        Path  = VirtualPath + "demo.docx",
                        Query = ""
                    };
                    var fileUri = uri.ToString();

                    ServiceConverter.GetConvertedUri(fileUri, "docx", "docx", Guid.NewGuid().ToString(), false, out convertUri);
                }
                catch
                {
                    convertUri = string.Empty;
                }

                _haveExternalIP = !string.IsNullOrEmpty(convertUri);
            }

            return(_haveExternalIP.Value);
        }
        // get files information
        public static List <Dictionary <string, object> > GetFilesInfo(string fileId = null)
        {
            var files = new List <Dictionary <string, object> >();

            // run through all the files from the directory
            foreach (var file in GetStoredFiles())
            {
                // write file parameters to the file object
                var dictionary = new Dictionary <string, object>();
                dictionary.Add("version", GetFileVersion(file.Name, null));
                dictionary.Add("id", ServiceConverter.GenerateRevisionId(_Default.CurUserHostAddress(null) + "/" + file.Name + "/" + File.GetLastWriteTime(_Default.StoragePath(file.Name, null)).GetHashCode()));
                dictionary.Add("contentLength", Math.Round(file.Length / 1024.0, 2) + " KB");
                dictionary.Add("pureContentLength", file.Length);
                dictionary.Add("title", file.Name);
                dictionary.Add("updated", file.LastWriteTime.ToString());
                if (fileId != null)
                {
                    // if file id is defined and it is equal to the document key value
                    if (fileId.Equals(dictionary["id"]))
                    {
                        files.Add(dictionary);  // add file object to the files
                        break;
                    }
                }
                else
                {
                    files.Add(dictionary);
                }
            }

            return(files);
        }
        /// <summary>
        ///     Method returning filtered courses
        /// </summary>
        /// <param name="filter">Filter to select specific courses</param>
        /// <returns>IEnumerable of DtoService</returns>
        public async Task <IEnumerable <DtoService> > GetCoursesWithoutCustomer(string customerEmail)
        {
            var ret = new ObservableCollection <DtoService>();

            try
            {
                using (var data = Context)
                {
                    var services = await data.Service
                                   .Where
                                       (s =>
                                       s.ServiceType.isCourse &&
                                       s.Customer.All(c => c.email != customerEmail)
                                       )
                                   .Take(TakeTop).ToListAsync();

                    foreach (var course in services)
                    {
                        ret.Add(ServiceConverter.DataAccessToDto(course));
                    }
                }
            }
            catch (Exception e)
            {
                ret = null;
            }
            return(ret);
        }
Beispiel #4
0
 public void Init(ServiceConverter serviceConverter, Transform[] topVerticesPoints, Transform[] PPoints, Slider[] sliders)
 {
     this.serviceConverter  = serviceConverter;
     this.topVerticesPoints = topVerticesPoints;
     this.PPoints           = PPoints;
     this.sliders           = sliders;
 }
        public static string GetExternalUri(string localUri)
        {
            try
            {
                var uri = HttpRuntime.Cache.Get(localUri) as string;
                if (string.IsNullOrEmpty(uri))
                {
                    var webRequest = (HttpWebRequest)WebRequest.Create(localUri);

                    // hack. http://ubuntuforums.org/showthread.php?t=1841740
                    if (IsMono)
                    {
                        ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                    }

                    using (var response = webRequest.GetResponse())
                        using (var responseStream = response.GetResponseStream())
                        {
                            var key = ServiceConverter.GenerateRevisionId(localUri);
                            uri = ServiceConverter.GetExternalUri(responseStream, response.ContentLength, response.ContentType, key);
                        }
                    HttpRuntime.Cache.Remove(localUri);
                    HttpRuntime.Cache.Insert(localUri, uri, null, DateTime.Now.Add(TimeSpan.FromMinutes(2)), Cache.NoSlidingExpiration);
                }
                return(uri);
            }
            catch (Exception)
            {
            }
            return(localUri);
        }
        public static List <Dictionary <string, object> > GetFilesInfo(string fileId = null)
        {
            var files = new List <Dictionary <string, object> >();

            foreach (var file in GetStoredFiles())
            {
                var dictionary = new Dictionary <string, object>();
                dictionary.Add("version", GetFileVersion(file.Name, null));
                dictionary.Add("id", ServiceConverter.GenerateRevisionId(_Default.CurUserHostAddress(null) + "/" + file.Name + "/" + File.GetLastWriteTime(_Default.StoragePath(file.Name, null)).GetHashCode()));
                dictionary.Add("contentLength", Math.Round(file.Length / 1024.0, 2) + " KB");
                dictionary.Add("pureContentLength", file.Length);
                dictionary.Add("title", file.Name);
                dictionary.Add("updated", file.LastWriteTime.ToString());
                if (fileId != null)
                {
                    if (fileId.Equals(dictionary["id"]))
                    {
                        files.Add(dictionary);
                        break;
                    }
                }
                else
                {
                    files.Add(dictionary);
                }
            }

            return(files);
        }
Beispiel #7
0
        public static bool HaveExternalIP()
        {
            if (!_haveExternalIP.HasValue)
            {
                string convertUri;
                try
                {
                    var uri = new UriBuilder(HttpContext.Current.Request.Url)
                    {
                        Path = HttpRuntime.AppDomainAppVirtualPath + "/"
                               + WebConfigurationManager.AppSettings["storage-path"]
                               + CurUserHostAddress + "/"
                               + "demo.docx",
                        Query = ""
                    };
                    var fileUri = uri.ToString();

                    ServiceConverter.GetConvertedUri(fileUri, "docx", "docx", Guid.NewGuid().ToString(), false, out convertUri);
                }
                catch
                {
                    convertUri = string.Empty;
                }

                _haveExternalIP = !string.IsNullOrEmpty(convertUri);
            }

            return(_haveExternalIP.Value);
        }
        private static void Convert(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try
            {
                var fileName = Path.GetFileName(context.Request["filename"]);
                var fileUri  = DocManagerHelper.GetFileUri(fileName, true);

                var extension         = (Path.GetExtension(fileUri) ?? "").Trim('.');
                var internalExtension = DocManagerHelper.GetInternalExtension(FileUtility.GetFileType(fileName)).Trim('.');

                if (DocManagerHelper.ConvertExts.Contains("." + extension) &&
                    !string.IsNullOrEmpty(internalExtension))
                {
                    var key = ServiceConverter.GenerateRevisionId(fileUri);

                    string newFileUri;
                    var    result = ServiceConverter.GetConvertedUri(fileUri, extension, internalExtension, key, true, out newFileUri);
                    if (result != 100)
                    {
                        context.Response.Write("{ \"step\" : \"" + result + "\", \"filename\" : \"" + fileName + "\"}");
                        return;
                    }

                    var correctName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "." + internalExtension);

                    var req = (HttpWebRequest)WebRequest.Create(newFileUri);

                    using (var stream = req.GetResponse().GetResponseStream())
                    {
                        if (stream == null)
                        {
                            throw new Exception("Stream is null");
                        }
                        const int bufferSize = 4096;

                        using (var fs = File.Open(DocManagerHelper.StoragePath(correctName), FileMode.Create))
                        {
                            var buffer = new byte[bufferSize];
                            int readed;
                            while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                            {
                                fs.Write(buffer, 0, readed);
                            }
                        }
                    }

                    Remove(fileName);
                    fileName = correctName;
                    DocManagerHelper.CreateMeta(fileName, context.Request.Cookies.GetOrDefault("uid", ""), context.Request.Cookies.GetOrDefault("uname", ""));
                }

                context.Response.Write("{ \"filename\" : \"" + fileName + "\"}");
            }
            catch (Exception e)
            {
                context.Response.Write("{ \"error\": \"" + e.Message + "\"}");
            }
        }
Beispiel #9
0
 public void Init(ServiceConverter serviceConverter, Transform[] topLPivots, Transform[] parallelograms, Transform[] PPoints, Transform endEffector)
 {
     this.serviceConverter = serviceConverter;
     this.topLPivots       = topLPivots;
     this.parallelograms   = parallelograms;
     this.PPoints          = PPoints;
     this.endEffector      = endEffector;
 }
        public async Task <ObservableCollection <SingleService> > GetSingleServices(ServiceFilter filter)
        {
            filter.IsCourse = false;
            var ret = new ObservableCollection <SingleService>();

            foreach (var c in await Post <ServiceFilter, ObservableCollection <DtoService> >("GetServices", filter))
            {
                ret.Add(ServiceConverter.DtoToViewModelSingleService(c));
            }
            return(ret);
        }
        public static string DoConvert(HttpContext context)
        {
            _fileName = context.Request["filename"];

            var extension         = (Path.GetExtension(_fileName) ?? "").Trim('.');
            var internalExtension = FileType.GetInternalExtension(_fileName).Trim('.');

            if (ConvertExts.Contains("." + extension) &&
                !string.IsNullOrEmpty(internalExtension))
            {
                var key = ServiceConverter.GenerateRevisionId(FileUri(_fileName));

                string newFileUri;
                var    result = ServiceConverter.GetConvertedUri(FileUri(_fileName), extension, internalExtension, key, true, out newFileUri);
                if (result != 100)
                {
                    return("{ \"step\" : \"" + result + "\", \"filename\" : \"" + _fileName + "\"}");
                }

                var fileName = GetCorrectName(Path.GetFileNameWithoutExtension(_fileName) + "." + internalExtension);

                var req = (HttpWebRequest)WebRequest.Create(newFileUri);

                // hack. http://ubuntuforums.org/showthread.php?t=1841740
                if (IsMono)
                {
                    ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                }

                using (var stream = req.GetResponse().GetResponseStream())
                {
                    if (stream == null)
                    {
                        throw new Exception("Stream is null");
                    }
                    const int bufferSize = 4096;

                    using (var fs = File.Open(StoragePath(fileName, null), FileMode.Create))
                    {
                        var buffer = new byte[bufferSize];
                        int readed;
                        while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                        {
                            fs.Write(buffer, 0, readed);
                        }
                    }
                }

                File.Delete(StoragePath(_fileName, null));
                _fileName = fileName;
            }

            return("{ \"filename\" : \"" + _fileName + "\"}");
        }
Beispiel #12
0
        public void Init(ServiceConverter serviceConverter, Vector3[] centresSpheres, double[,] a, double[] b, double[] c, double[] coefficients)
        {
            this.serviceConverter = serviceConverter;
            this.centresSpheres   = centresSpheres;
            this.a            = a;
            this.b            = b;
            this.c            = c;
            this.coefficients = coefficients;

            singularityAppearance = ScriptableObject.CreateInstance <SingularityAppearance>();
            singularityAppearance.Init(serviceConverter);
        }
        /// <summary>
        ///     Method returning filtered courses
        /// </summary>
        /// <param name="filter">Filter to select specific courses</param>
        /// <returns>IEnumerable of DtoService</returns>
        public async Task <IEnumerable <DtoService> > GetServices(ServiceFilter filter = null)
        {
            var ret = new ObservableCollection <DtoService>();

            try
            {
                using (var data = Context)
                {
                    if (filter == null)
                    {
                        foreach (
                            var course in
                            await data.Service.Where(s => s.ServiceType.isCourse).Take(TakeTop).ToListAsync())
                        {
                            ret.Add(ServiceConverter.DataAccessToDto(course));
                        }
                    }
                    else
                    {
                        var services = await data.Service
                                       .Where
                                           (s =>
                                           s.ServiceType.isCourse == filter.IsCourse
                                           &&
                                           (string.IsNullOrEmpty(filter.Customer) ||
                                            s.Customer.Any(
                                                c => c.name.Contains(filter.Customer) || c.surname.Contains(filter.Customer)))
                                           &&
                                           (string.IsNullOrEmpty(filter.Instructor) || s.Employee.name.Contains(filter.Instructor) ||
                                            s.Employee.surname.Contains(filter.Instructor)) &&
                                           (filter.ServiceTypeId == null || s.ServiceType.id == filter.ServiceTypeId) &&
                                           (filter.SportId == null || s.ServiceType.sportTypeID == filter.SportId) &&
                                           (string.IsNullOrEmpty(filter.CustomerEmail) || s.Customer.Any(c => c.email == filter.CustomerEmail))
                                           )
                                       .Take(TakeTop).ToListAsync();

                        foreach (var course in services)
                        {
                            ret.Add(ServiceConverter.DataAccessToDto(course));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                ret = null;
            }
            return(ret);
        }
        /// <summary>
        ///     Method returning course with specific id
        /// </summary>
        /// <param name="courseId">Id of course</param>
        /// <returns>Dto object of course</returns>
        public async Task <DtoService> GetCourse(int courseId)
        {
            DtoService course = null;

            using (var data = Context)
            {
                var service = await data.Service.FirstOrDefaultAsync(c => c.id == courseId);

                if (service != null)
                {
                    course = ServiceConverter.DataAccessToDto(service);
                }
            }
            return(course);
        }
Beispiel #15
0
        public static string DoConvert(string fileId)
        {
            _fileName = fileId;

            var extension         = (Path.GetExtension(_fileName) ?? "").Trim('.');
            var internalExtension = FileType.GetInternalExtension(_fileName).Trim('.');

            if (ConvertExts.Contains("." + extension) &&
                !string.IsNullOrEmpty(internalExtension))
            {
                var key = ServiceConverter.GenerateRevisionId(FileUri(_fileName));

                string newFileUri;
                var    result = ServiceConverter.GetConvertedUri(FileUri(_fileName), extension, internalExtension, key, true, out newFileUri);
                if (result != 100)
                {
                    return("{ \"step\" : \"" + result + "\", \"filename\" : \"" + _fileName + "\"}");
                }

                var fileName = GetCorrectName(Path.GetFileNameWithoutExtension(_fileName) + "." + internalExtension);

                var req = (HttpWebRequest)WebRequest.Create(newFileUri);

                using (var stream = req.GetResponse().GetResponseStream())
                {
                    if (stream == null)
                    {
                        throw new Exception("Stream is null");
                    }
                    const int bufferSize = 4096;

                    using (var fs = File.Open(StoragePath + fileName, FileMode.Create))
                    {
                        var buffer = new byte[bufferSize];
                        int readed;
                        while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                        {
                            fs.Write(buffer, 0, readed);
                        }
                    }
                }

                File.Delete(StoragePath + _fileName);
                _fileName = fileName;
            }

            return("{ \"filename\" : \"" + _fileName + "\"}");
        }
Beispiel #16
0
    private void SetupVariables()
    {
        serviceConverter   = new ServiceConverter();
        serviceInitializer = ScriptableObject.CreateInstance <ServiceInitializer>();
        serviceInitializer.Init(serviceConverter, topVerticesPoints, PPoints, sliders);

        simulation = gameObject.AddComponent <PickAndPlaceSimulation>();

        thetas = new double[TOTAL_NO_JOINTS] {
            0.0, 0.0, 0.0
        };
        Ei = new double[TOTAL_NO_JOINTS];
        Fi = new double[TOTAL_NO_JOINTS];
        Gi = new double[TOTAL_NO_JOINTS];
        L  = DeltaRobotIKUtils.L;
        l  = DeltaRobotIKUtils.l;
    }
 static void Main(string[] args)
 {
     try
     {
         ServiceConverter serviceConverter = new ServiceConverter();
         serviceConverter.GenerateFileConverted();
     }
     catch (Exception e)
     {
         Console.WriteLine("Exception: " + e.Message);
     }
     finally
     {
         Console.WriteLine(@"Arquivos invoice.data gerado no caminho C:\Users\treim\OneDrive\Documentos\Utils\invoice.data");
         Console.ReadKey();
     }
 }
        // GET api/editor
        public HttpResponseMessage Get(string fileId)
        {
            var fileName    = fileId;
            var fileUri     = DocumentService.FileUri(fileName);
            var key         = ServiceConverter.GenerateRevisionId(/*DocumentService.CurUserHostAddress +*/ "__1/" + Path.GetFileName(fileUri));
            var validateKey = ServiceConverter.GenerateValidateKey(key);

            return(Request.CreateResponse(HttpStatusCode.OK, new
            {
                type = "desktop",
                documentType = "text",
                fileName = fileName,
                fileUri = fileUri,
                key = key,
                validateKey = validateKey,
                isEditable = true
            }));
        }
Beispiel #19
0
    private void Setup()
    {
        L              = DeltaRobotFKUtils.L;
        l              = DeltaRobotFKUtils.l;
        NO_OF_LEGS     = DeltaRobotFKUtils.NO_OF_LEGS;
        coefficients   = new double[NO_OF_LEGS];
        a              = new double[DeltaRobotFKUtils.FIRST_ROW_NUMBER, DeltaRobotFKUtils.FIRST_COLUMN_NUMBER];
        b              = new double[DeltaRobotFKUtils.SECOND_NUMBER];
        c              = new double[DeltaRobotFKUtils.THIRD_NUMBER];
        thetas         = new double[NO_OF_LEGS];
        centresCircles = new Vector3[NO_OF_LEGS];

        serviceConverter   = new ServiceConverter();
        serviceInitializer = ScriptableObject.CreateInstance <ServiceInitializer>();
        serviceInitializer.Init(serviceConverter, topVerticesPoints, PPoints, sliders);

        legsRotation = ScriptableObject.CreateInstance <LegsRotation>();
        legsRotation.Init(serviceConverter, topLPivots, parallelograms, PPoints, endEffector);
    }
Beispiel #20
0
        public static bool HaveExternalIP()
        {
            if (!_haveExternalIP.HasValue)
            {
                string convertUri;
                try
                {
                    var uri = Host;
                    uri.Path = VirtualPath + "demo.docx";
                    var fileUri = uri.ToString();

                    ServiceConverter.GetConvertedUri(fileUri, "docx", "docx", Guid.NewGuid().ToString(), false, out convertUri);
                }
                catch
                {
                    convertUri = string.Empty;
                }

                _haveExternalIP = !string.IsNullOrEmpty(convertUri);
            }

            return(_haveExternalIP.Value);
        }
Beispiel #21
0
 public static string GetExternalUri(string localUri)
 {
     try
     {
         var uri = HttpRuntime.Cache.Get(localUri) as string;
         if (string.IsNullOrEmpty(uri))
         {
             var webRequest = WebRequest.Create(localUri);
             using (var response = webRequest.GetResponse())
                 using (var responseStream = response.GetResponseStream())
                 {
                     var key = ServiceConverter.GenerateRevisionId(localUri);
                     uri = ServiceConverter.GetExternalUri(responseStream, response.ContentLength, response.ContentType, key);
                 }
             HttpRuntime.Cache.Insert(localUri, uri, null, DateTime.UtcNow.Add(TimeSpan.FromMinutes(2)), Cache.NoSlidingExpiration);
         }
         return(uri);
     }
     catch (Exception)
     {
     }
     return(localUri);
 }
        /// <summary>
        ///     Adds new course to database
        /// </summary>
        /// <param name="service">Dtoobject course to add</param>
        /// <returns>Is Success</returns>
        public async Task <bool> AddService(DtoService service)
        {
            try
            {
                using (var data = Context)
                {
                    var databaseItem = ServiceConverter.DtoToDataAccess(service);
                    data.Service.Add(databaseItem);
                    foreach (var d in service.Dates)
                    {
                        data.ServiceDate.Add(new ServiceDate {
                            serviceID = service.Id, date = d
                        });
                    }
                    await data.SaveChangesAsync();

                    return(true);
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
        public static string DoConvert(HttpContext context)
        {
            _fileName = context.Request["filename"];

            var extension         = (Path.GetExtension(_fileName) ?? "").Trim('.');
            var internalExtension = FileType.GetInternalExtension(_fileName).Trim('.');

            if (ConvertExts.Contains("." + extension) &&
                !string.IsNullOrEmpty(internalExtension))
            {
                var key = ServiceConverter.GenerateRevisionId(FileUri(_fileName));

                string newFileUri;
                var    result = ServiceConverter.GetConvertedUri(FileUri(_fileName), extension, internalExtension, key, true, out newFileUri);
                if (result != 100)
                {
                    return("{ \"step\" : \"" + result + "\", \"filename\" : \"" + _fileName + "\"}");
                }

                var fileName = GetCorrectName(Path.GetFileNameWithoutExtension(_fileName) + "." + internalExtension);

                var req = (HttpWebRequest)WebRequest.Create(newFileUri);

                // hack. http://ubuntuforums.org/showthread.php?t=1841740
                if (IsMono)
                {
                    ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                }

                using (var stream = req.GetResponse().GetResponseStream())
                {
                    if (stream == null)
                    {
                        throw new Exception("Stream is null");
                    }
                    const int bufferSize = 4096;

                    using (var fs = File.Open(StoragePath(fileName, null), FileMode.Create))
                    {
                        var buffer = new byte[bufferSize];
                        int readed;
                        while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                        {
                            fs.Write(buffer, 0, readed);
                        }
                    }
                }

                var storagePath = StoragePath(_fileName, null);
                var histDir     = HistoryDir(storagePath);
                File.Delete(storagePath);
                if (Directory.Exists(histDir))
                {
                    Directory.Delete(histDir, true);
                }

                _fileName = fileName;
                histDir   = HistoryDir(StoragePath(_fileName, null));
                Directory.CreateDirectory(histDir);
                File.WriteAllText(Path.Combine(histDir, "createdInfo.json"), new JavaScriptSerializer().Serialize(new Dictionary <string, object> {
                    { "created", DateTime.Now.ToString() },
                    { "id", context.Request.Cookies.GetOrDefault("uid", "uid-1") },
                    { "name", context.Request.Cookies.GetOrDefault("uname", "John Smith") }
                }));
            }

            return("{ \"filename\" : \"" + _fileName + "\"}");
        }
        public static int processSave(Dictionary <string, object> fileData, string fileName, string userAddress)
        {
            var downloadUri = (string)fileData["url"];
            var curExt      = Path.GetExtension(fileName);
            var downloadExt = Path.GetExtension(downloadUri) ?? "";
            var newFileName = fileName;

            if (!downloadExt.Equals(curExt, StringComparison.InvariantCultureIgnoreCase))
            {
                try
                {
                    string newFileUri;
                    ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileUri);
                    if (string.IsNullOrEmpty(newFileUri))
                    {
                        newFileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                    }
                    else
                    {
                        downloadUri = newFileUri;
                    }
                }
                catch (Exception)
                {
                    newFileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                }
            }

            // hack. http://ubuntuforums.org/showthread.php?t=1841740
            if (_Default.IsMono)
            {
                ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
            }

            var storagePath = _Default.StoragePath(newFileName, userAddress);
            var histDir     = _Default.HistoryDir(storagePath);

            if (!Directory.Exists(histDir))
            {
                Directory.CreateDirectory(histDir);
            }

            var versionDir = _Default.VersionDir(histDir, _Default.GetFileVersion(histDir));

            if (!Directory.Exists(versionDir))
            {
                Directory.CreateDirectory(versionDir);
            }

            File.Copy(_Default.StoragePath(fileName, userAddress), Path.Combine(versionDir, "prev" + curExt));

            DownloadToFile(downloadUri, storagePath);
            DownloadToFile((string)fileData["changesurl"], Path.Combine(versionDir, "diff.zip"));

            var hist = fileData.ContainsKey("changeshistory") ? (string)fileData["changeshistory"] : null;

            if (string.IsNullOrEmpty(hist) && fileData.ContainsKey("history"))
            {
                var jss = new JavaScriptSerializer();
                hist = jss.Serialize(fileData["history"]);
            }

            if (!string.IsNullOrEmpty(hist))
            {
                File.WriteAllText(Path.Combine(versionDir, "changes.json"), hist);
            }

            File.WriteAllText(Path.Combine(versionDir, "key.txt"), (string)fileData["key"]);

            string forcesavePath = _Default.ForcesavePath(newFileName, userAddress, false);

            if (!forcesavePath.Equals(""))
            {
                File.Delete(forcesavePath);
            }

            return(0);
        }
        // converting a file
        public static string DoConvert(HttpContext context)
        {
            string fileData;

            try
            {
                using (var receiveStream = context.Request.InputStream)
                    using (var readStream = new StreamReader(receiveStream))
                    {
                        fileData = readStream.ReadToEnd();
                        if (string.IsNullOrEmpty(fileData))
                        {
                            context.Response.Write("{\"error\":1,\"message\":\"Request stream is empty\"}");
                        }
                    }
            }
            catch (Exception e)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
            }

            var jss  = new JavaScriptSerializer();
            var body = jss.Deserialize <Dictionary <string, object> >(fileData);

            _fileName = Path.GetFileName(body["filename"].ToString());
            var filePass = body["filePass"] != null ? body["filePass"].ToString() : null;
            var lang     = context.Request.Cookies.GetOrDefault("ulang", null);

            var extension         = (Path.GetExtension(_fileName).ToLower() ?? "").Trim('.');
            var internalExtension = FileType.GetInternalExtension(_fileName).Trim('.');

            // check if the file with such an extension can be converted
            if (ConvertExts.Contains("." + extension) &&
                !string.IsNullOrEmpty(internalExtension))
            {
                // generate document key
                var key = ServiceConverter.GenerateRevisionId(FileUri(_fileName, true));

                var fileUrl = new UriBuilder(_Default.GetServerUrl(true));
                fileUrl.Path = HttpRuntime.AppDomainAppVirtualPath
                               + (HttpRuntime.AppDomainAppVirtualPath.EndsWith("/") ? "" : "/")
                               + "webeditor.ashx";
                fileUrl.Query = "type=download&fileName=" + HttpUtility.UrlEncode(_fileName)
                                + "&userAddress=" + HttpUtility.UrlEncode(HttpContext.Current.Request.UserHostAddress);

                // get the url to the converted file
                string newFileUri;
                var    result = ServiceConverter.GetConvertedUri(fileUrl.ToString(), extension, internalExtension, key, true, out newFileUri, filePass, lang);
                if (result != 100)
                {
                    return("{ \"step\" : \"" + result + "\", \"filename\" : \"" + _fileName + "\"}");
                }

                // get a file name of an internal file extension with an index if the file with such a name already exists
                var fileName = GetCorrectName(Path.GetFileNameWithoutExtension(_fileName) + "." + internalExtension);

                var req = (HttpWebRequest)WebRequest.Create(newFileUri);

                VerifySSL();

                using (var stream = req.GetResponse().GetResponseStream())  // get response stream of the converting file
                {
                    if (stream == null)
                    {
                        throw new Exception("Stream is null");
                    }
                    const int bufferSize = 4096;

                    using (var fs = File.Open(StoragePath(fileName, null), FileMode.Create))
                    {
                        var buffer = new byte[bufferSize];
                        int readed;
                        while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                        {
                            fs.Write(buffer, 0, readed);  // write bytes to the output stream
                        }
                    }
                }

                // remove the original file and its history if it exists
                var storagePath = StoragePath(_fileName, null);
                var histDir     = HistoryDir(storagePath);
                File.Delete(storagePath);
                if (Directory.Exists(histDir))
                {
                    Directory.Delete(histDir, true);
                }

                // create meta information about the converted file with user id and name specified
                _fileName = fileName;
                var id   = context.Request.Cookies.GetOrDefault("uid", null);
                var user = Users.getUser(id);  // get the user
                DocEditor.CreateMeta(_fileName, user.id, user.name, null);
            }

            return("{ \"filename\" : \"" + _fileName + "\"}");
        }
Beispiel #26
0
        private static void Track(HttpContext context)
        {
            var userAddress = context.Request["userAddress"];
            var fileName    = context.Request["fileName"];

            string body;

            try
            {
                using (var receiveStream = context.Request.InputStream)
                    using (var readStream = new StreamReader(receiveStream))
                    {
                        body = readStream.ReadToEnd();
                    }
            }
            catch (Exception e)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
            }

            var jss = new JavaScriptSerializer();

            if (string.IsNullOrEmpty(body))
            {
                return;
            }
            var fileData = jss.Deserialize <Dictionary <string, object> >(body);

            if (JwtManager.Enabled)
            {
                if (fileData.ContainsKey("token"))
                {
                    fileData = jss.Deserialize <Dictionary <string, object> >(JwtManager.Decode(fileData["token"].ToString()));
                }
                else if (context.Request.Headers.AllKeys.Contains("Authorization", StringComparer.InvariantCultureIgnoreCase))
                {
                    var headerToken = context.Request.Headers.Get("Authorization").Substring("Bearer ".Length);
                    fileData = (Dictionary <string, object>)jss.Deserialize <Dictionary <string, object> >(JwtManager.Decode(headerToken))["payload"];
                }
                else
                {
                    throw new Exception("Expected JWT");
                }
            }

            var status = (TrackerStatus)(int)fileData["status"];

            switch (status)
            {
            case TrackerStatus.MustSave:
            case TrackerStatus.Corrupted:
                var downloadUri = (string)fileData["url"];

                var curExt      = Path.GetExtension(fileName);
                var downloadExt = Path.GetExtension(downloadUri) ?? "";
                if (!downloadExt.Equals(curExt, StringComparison.InvariantCultureIgnoreCase))
                {
                    var key = ServiceConverter.GenerateRevisionId(downloadUri);

                    try
                    {
                        string newFileUri;
                        ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, key, false, out newFileUri);
                        downloadUri = newFileUri;
                    }
                    catch (Exception ex)
                    {
                        fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                    }
                }

                // hack. http://ubuntuforums.org/showthread.php?t=1841740
                if (_Default.IsMono)
                {
                    ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                }

                var saved = 1;
                try
                {
                    var storagePath = _Default.StoragePath(fileName, userAddress);
                    var histDir     = _Default.HistoryDir(storagePath);
                    var versionDir  = _Default.VersionDir(histDir, _Default.GetFileVersion(histDir) + 1);

                    if (!Directory.Exists(versionDir))
                    {
                        Directory.CreateDirectory(versionDir);
                    }

                    File.Copy(storagePath, Path.Combine(versionDir, "prev" + curExt));

                    DownloadToFile(downloadUri, _Default.StoragePath(fileName, userAddress));
                    DownloadToFile((string)fileData["changesurl"], Path.Combine(versionDir, "diff.zip"));

                    var hist = fileData.ContainsKey("changeshistory") ? (string)fileData["changeshistory"] : null;
                    if (string.IsNullOrEmpty(hist) && fileData.ContainsKey("history"))
                    {
                        hist = jss.Serialize(fileData["history"]);
                    }

                    if (!string.IsNullOrEmpty(hist))
                    {
                        File.WriteAllText(Path.Combine(versionDir, "changes.json"), hist);
                    }

                    File.WriteAllText(Path.Combine(versionDir, "key.txt"), (string)fileData["key"]);
                }
                catch (Exception)
                {
                    saved = 0;
                }

                break;
            }
            context.Response.Write("{\"error\":0}");
        }
        private static void Save(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            var downloadUri = context.Request["fileuri"].Replace(":80/", ":80/office/");
            var fileName    = context.Request["filename"];

            if (string.IsNullOrEmpty(downloadUri) || string.IsNullOrEmpty(fileName))
            {
                context.Response.Write("error");
                return;
            }

            var newType     = Path.GetExtension(downloadUri).Trim('.');
            var currentType = (context.Request["filetype"] ?? Path.GetExtension(fileName)).Trim('.');

            if (newType.ToLower() != currentType.ToLower())
            {
                var key = ServiceConverter.GenerateRevisionId(downloadUri);

                string newFileUri;
                try
                {
                    var result = ServiceConverter.GetConvertedUri(downloadUri, newType, currentType, key, false, out newFileUri);
                    if (result != 100)
                    {
                        throw new Exception();
                    }
                }
                catch (Exception)
                {
                    context.Response.Write("error");
                    return;
                }
                downloadUri = newFileUri;
                newType     = currentType;
            }

            fileName = Path.GetFileNameWithoutExtension(fileName) + "." + newType;

            var req = (HttpWebRequest)WebRequest.Create(downloadUri);

            try
            {
                using (var stream = req.GetResponse().GetResponseStream())
                {
                    if (stream == null)
                    {
                        throw new Exception("stream is null");
                    }
                    const int bufferSize = 4096;

                    using (var fs = File.Open(DocumentService.StoragePath + fileName, FileMode.Create))
                    {
                        var buffer = new byte[bufferSize];
                        int readed;
                        while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                        {
                            fs.Write(buffer, 0, readed);
                        }
                    }
                }
            }
            catch (Exception)
            {
                context.Response.Write("error");
                return;
            }

            context.Response.Write("success");
        }
        public static int processForceSave(Dictionary <string, object> fileData, string fileName, string userAddress)
        {
            var downloadUri = (string)fileData["url"];

            string curExt      = Path.GetExtension(fileName);
            string downloadExt = Path.GetExtension(downloadUri);
            var    newFileName = fileName;

            if (!curExt.Equals(downloadExt))
            {
                try
                {
                    string newFileUri;
                    var    result = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileUri);
                    if (string.IsNullOrEmpty(newFileUri))
                    {
                        newFileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                    }
                    else
                    {
                        downloadUri = newFileUri;
                    }
                }
                catch (Exception)
                {
                    newFileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                }
            }

            // hack. http://ubuntuforums.org/showthread.php?t=1841740
            if (_Default.IsMono)
            {
                ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
            }

            string  forcesavePath = "";
            Boolean isSubmitForm  = fileData["forcesavetype"].ToString().Equals("3");

            if (isSubmitForm)
            {
                if (newFileName.Equals(fileName))
                {
                    newFileName = _Default.GetCorrectName(fileName, userAddress);
                }
                forcesavePath = _Default.StoragePath(newFileName, userAddress);
            }
            else
            {
                forcesavePath = _Default.ForcesavePath(newFileName, userAddress, false);
                if (forcesavePath.Equals(""))
                {
                    forcesavePath = _Default.ForcesavePath(newFileName, userAddress, true);
                }
            }

            DownloadToFile(downloadUri, forcesavePath);

            if (isSubmitForm)
            {
                var jss     = new JavaScriptSerializer();
                var actions = jss.Deserialize <List <object> >(jss.Serialize(fileData["actions"]));
                var action  = jss.Deserialize <Dictionary <string, object> >(jss.Serialize(actions[0]));
                var user    = action["userid"].ToString();
                DocEditor.CreateMeta(newFileName, user, "Filling Form", userAddress);
            }

            return(0);
        }
        private static void Track(HttpContext context)
        {
            var userAddress = context.Request["userAddress"];
            var fileName    = context.Request["fileName"];

            string body;

            try
            {
                using (var receiveStream = context.Request.InputStream)
                    using (var readStream = new StreamReader(receiveStream))
                    {
                        body = readStream.ReadToEnd();
                    }
            }
            catch (Exception e)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
            }

            var jss = new JavaScriptSerializer();

            if (string.IsNullOrEmpty(body))
            {
                return;
            }
            var fileData = jss.Deserialize <Dictionary <string, object> >(body);
            var status   = (TrackerStatus)(int)fileData["status"];

            switch (status)
            {
            case TrackerStatus.MustSave:
            case TrackerStatus.Corrupted:
                var downloadUri = (string)fileData["url"];

                var curExt      = Path.GetExtension(fileName);
                var downloadExt = Path.GetExtension(downloadUri) ?? "";
                if (!downloadExt.Equals(curExt, StringComparison.InvariantCultureIgnoreCase))
                {
                    var key = ServiceConverter.GenerateRevisionId(downloadUri);

                    try
                    {
                        string newFileUri;
                        ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, key, false, out newFileUri);
                        downloadUri = newFileUri;
                    }
                    catch (Exception ex)
                    {
                        fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                    }
                }

                var req = (HttpWebRequest)WebRequest.Create(downloadUri);

                // hack. http://ubuntuforums.org/showthread.php?t=1841740
                if (_Default.IsMono)
                {
                    ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                }

                var saved = 1;
                try
                {
                    using (var stream = req.GetResponse().GetResponseStream())
                    {
                        if (stream == null)
                        {
                            throw new Exception("stream is null");
                        }
                        const int bufferSize = 4096;

                        var storagePath = _Default.StoragePath(fileName, userAddress);
                        using (var fs = File.Open(storagePath, FileMode.Create))
                        {
                            var buffer = new byte[bufferSize];
                            int readed;
                            while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                            {
                                fs.Write(buffer, 0, readed);
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    saved = 0;
                }

                break;
            }
            context.Response.Write("{\"error\":0}");
        }
Beispiel #30
0
        private static void Save(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            var downloadUri = context.Request["fileuri"];
            var fileName    = context.Request["filename"];

            if (string.IsNullOrEmpty(downloadUri) || string.IsNullOrEmpty(fileName))
            {
                context.Response.Write("error");
                return;
            }

            var newType     = Path.GetExtension(downloadUri).Trim('.');
            var currentType = (context.Request["filetype"] ?? Path.GetExtension(fileName)).Trim('.');

            if (newType.ToLower() != currentType.ToLower())
            {
                var key = ServiceConverter.GenerateRevisionId(downloadUri);

                string newFileUri;
                try
                {
                    var result = ServiceConverter.GetConvertedUri(downloadUri, newType, currentType, key, false, out newFileUri);
                    if (result != 100)
                    {
                        throw new Exception();
                    }
                }
                catch (Exception)
                {
                    context.Response.Write("error");
                    return;
                }
                downloadUri = newFileUri;
                newType     = currentType;
            }

            fileName = Path.GetFileNameWithoutExtension(fileName) + "." + newType;

            var req = (HttpWebRequest)WebRequest.Create(downloadUri);

            // hack. http://ubuntuforums.org/showthread.php?t=1841740
            if (_Default.IsMono)
            {
                ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
            }

            try
            {
                using (var stream = req.GetResponse().GetResponseStream())
                {
                    if (stream == null)
                    {
                        throw new Exception("stream is null");
                    }
                    const int bufferSize = 4096;

                    using (var fs = File.Open(_Default.StoragePath(fileName, null), FileMode.Create))
                    {
                        var buffer = new byte[bufferSize];
                        int readed;
                        while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                        {
                            fs.Write(buffer, 0, readed);
                        }
                    }
                }
            }
            catch (Exception)
            {
                context.Response.Write("error");
                return;
            }

            context.Response.Write("success");
        }