Ejemplo n.º 1
0
        /// <summary>
        /// Realiza el armado del repositorio de información XBRL
        /// </summary>
        /// <param name="listEntEstructuraInstancia">Estructura de los hechos que se van a registrar en el repositorio de informacion</param>
        /// <returns></returns>
        public List <EntBlockStoreDocumentosyFiltros> armarBlockStoreHashConsulta(List <EntEstructuraInstancia> listEntEstructuraInstancia)
        {
            var listadoDocumentos = new List <EntBlockStoreDocumentosyFiltros>();

            foreach (var itemEstructuraInstancia in listEntEstructuraInstancia)
            {
                var blockStoreDocumentosyFiltros = new EntBlockStoreDocumentosyFiltros
                {
                    registroBlockStore = new BsonDocument(),
                    filtrosBlockStore  = new BsonDocument(),
                    EsValorChunks      = false
                };

                var estructuraClone = (EntEstructuraInstancia)itemEstructuraInstancia.Clone();

                estructuraClone.Valor           = null;
                estructuraClone.ValorRedondeado = 0;

                itemEstructuraInstancia.codigoHashRegistro = UtilAbax.CalcularHash(estructuraClone.ToJson());

                var elemento = ConstEstandar.AperturaLlave;

                elemento += string.Format(ConstBlockStoreHechos.CodigoHashRegistro, itemEstructuraInstancia.codigoHashRegistro);
                blockStoreDocumentosyFiltros.CodigoHashRegistro = itemEstructuraInstancia.codigoHashRegistro;

                //elemento += string.Format(ConstBlockStoreHechos.Trimestre, itemEstructuraInstancia.Trimestre);
                //elemento += string.Format(ConstBlockStoreHechos.Ejercicio, itemEstructuraInstancia.Ejercicio);


                elemento += string.Format(ConstBlockStoreHechos.Taxonomia, itemEstructuraInstancia.EspacioNombresPrincipal);
                elemento += string.Format(ConstBlockStoreHechos.Entidad, itemEstructuraInstancia.Entidad.miId, itemEstructuraInstancia.Entidad.miEspaciodeNombresEntidad);
                elemento += !string.IsNullOrEmpty(itemEstructuraInstancia.Rol) ? string.Format(ConstBlockStoreHechos.Roll, itemEstructuraInstancia.Rol) : string.Empty;

                elemento += string.Format(ConstBlockStoreHechos.Concepto, itemEstructuraInstancia.Concepto.Id, itemEstructuraInstancia.Concepto.Nombre, itemEstructuraInstancia.EspacioNombresPrincipal, itemEstructuraInstancia.Concepto.EspacioNombres);

                if (itemEstructuraInstancia.Concepto.etiqueta != null && itemEstructuraInstancia.Concepto.etiqueta.Count > 0)
                {
                    string valorEtiqueta = "";
                    foreach (var etiqueta in itemEstructuraInstancia.Concepto.etiqueta)
                    {
                        if (etiqueta.roll.Equals("http://www.xbrl.org/2003/role/label"))
                        {
                            valorEtiqueta += string.Format(ConstBlockStoreHechos.EstructuraEtiqueta, etiqueta.lenguaje, etiqueta.valor.Replace(ConstEstandar.ComillaSimple, string.Empty), etiqueta.roll.Replace(ConstEstandar.ComillaSimple, string.Empty));
                            valorEtiqueta += ConstEstandar.SeparadorComa;
                        }
                    }

                    var etiquetas = string.Format(ConstBlockStoreHechos.ConceptoEtiqueta, valorEtiqueta.Substring(0, valorEtiqueta.Length + ConstEstandar.MenosTres));
                    elemento += etiquetas;
                }


                elemento += !string.IsNullOrEmpty(itemEstructuraInstancia.TipoBalance) ? string.Format(ConstBlockStoreHechos.Balance, itemEstructuraInstancia.TipoBalance) : string.Empty;

                elemento += string.Format(ConstBlockStoreHechos.ValorDocumentoTipoDato, itemEstructuraInstancia.IdTipoDato, itemEstructuraInstancia.EsTipoDatoNumerico.ToString().ToLower());
                if (itemEstructuraInstancia.EsTipoDatoNumerico)
                {
                    elemento += !string.IsNullOrEmpty(itemEstructuraInstancia.Valor) ? string.Format(ConstBlockStoreHechos.ValorDocumentoTipoDatoNumericoValorRedondeado, itemEstructuraInstancia.Valor, itemEstructuraInstancia.ValorRedondeado) : string.Empty;
                    elemento += !string.IsNullOrEmpty(itemEstructuraInstancia.Precision) ? string.Format(ConstBlockStoreHechos.ValorDocumentoTipoDatoNumericoPrecision, itemEstructuraInstancia.Precision) : string.Empty;
                    elemento += !string.IsNullOrEmpty(itemEstructuraInstancia.Decimales) ? string.Format(ConstBlockStoreHechos.ValorDocumentoTipoDatoNumericoDecimales, itemEstructuraInstancia.Decimales) : string.Empty;
                    elemento += string.Format(ConstBlockStoreHechos.ValorDocumentoTipoDatoNumericoFraccion, itemEstructuraInstancia.EsTipoDatoFraccion.ToString().ToLower());
                }
                else
                {
                    if (!String.IsNullOrWhiteSpace(itemEstructuraInstancia.Valor) && itemEstructuraInstancia.Valor.Length > ConstBlockStoreHechos.MAX_STRING_VALUE_LENGTH)
                    {
                        blockStoreDocumentosyFiltros.EsValorChunks = true;
                        blockStoreDocumentosyFiltros.ValorHecho    = itemEstructuraInstancia.Valor;
                        elemento += string.Format(ConstBlockStoreHechos.EsValorChunks, "true");
                    }
                    else
                    {
                        elemento += !string.IsNullOrEmpty(itemEstructuraInstancia.Valor) ? string.Format(ConstBlockStoreHechos.ValorDocumentoTipoDatoNumericoValor, WebUtility.HtmlEncode(itemEstructuraInstancia.Valor.Replace("\\", "/"))) : string.Empty;
                    }
                }
                elemento += string.Format(ConstBlockStoreHechos.ValorDocumentoTipoDatoValorNil, itemEstructuraInstancia.EsValorNil.ToString().ToLower());

                if (!itemEstructuraInstancia.Periodo.EsTipoInstante)
                {
                    elemento += string.Format(ConstBlockStoreHechos.PeriodoDuracion, itemEstructuraInstancia.Periodo.Tipo, string.Empty + BsonDateTime.Create(itemEstructuraInstancia.Periodo.FechaInicio).ToJson(), string.Empty + BsonDateTime.Create(itemEstructuraInstancia.Periodo.FechaFin).ToJson());
                }
                else
                {
                    elemento += string.Format(ConstBlockStoreHechos.PeriodoInstante, itemEstructuraInstancia.Periodo.Tipo, string.Empty + BsonDateTime.Create(itemEstructuraInstancia.Periodo.FechaInstante).ToJson());
                }

                var tipoMedidaNumerador = string.Empty;
                if (itemEstructuraInstancia.Medida != null)
                {
                    elemento += string.Format(ConstBlockStoreHechos.Medida, itemEstructuraInstancia.Medida.EsDivisoria.ToString().ToLower());
                    var tipoMedida = ConstBlockStoreHechos.TipoMedida;
                    foreach (var unidad in itemEstructuraInstancia.Medida.Medidas)
                    {
                        tipoMedida += string.Format(ConstBlockStoreHechos.TipoMedidaArray, unidad.Nombre, unidad.EspacioNombres);
                    }

                    tipoMedida = string.Format(ConstEstandar.AnidamientoDos, tipoMedida.Substring(ConstEstandar.NumeroCero, tipoMedida.Length + ConstEstandar.MenosUno), ConstEstandar.CierreCorchete);
                    if (itemEstructuraInstancia.Medida.EsDivisoria)
                    {
                        tipoMedidaNumerador = ConstBlockStoreHechos.TipoMedidaNumerador;
                        foreach (var unidad in itemEstructuraInstancia.Medida.MedidasNumerador)
                        {
                            tipoMedidaNumerador = tipoMedidaNumerador + string.Format(ConstBlockStoreHechos.TipoMedidaArray, unidad.Nombre, unidad.EspacioNombres);
                        }
                        tipoMedidaNumerador = string.Format(ConstEstandar.AnidamientoTres, tipoMedidaNumerador.Substring(ConstEstandar.NumeroCero, tipoMedidaNumerador.Length + ConstEstandar.MenosUno), ConstEstandar.CierreCorchete, ConstEstandar.CierreLlave);
                    }
                    else
                    {
                        tipoMedida += ConstEstandar.CierreLlave;
                    }
                    elemento += string.Format(ConstEstandar.AnidamientoDos, tipoMedida, tipoMedidaNumerador);
                }



                if (itemEstructuraInstancia.Dimension != null)
                {
                    var tipoDimension = ConstBlockStoreHechos.Dimension;

                    foreach (var dimension in itemEstructuraInstancia.Dimension)
                    {
                        tipoDimension += string.Format(ConstBlockStoreHechos.DimensionAtributos, dimension.Explicita.ToString().ToLower(), dimension.QNameDimension, dimension.IdDimension);

                        if (dimension.QNameItemMiembro != null)
                        {
                            tipoDimension += string.Format(ConstBlockStoreHechos.DimensionAtributosNombreElementoMiembro, dimension.QNameItemMiembro, dimension.IdItemMiembro.Replace("\n", "").Replace("'", "").Replace("\"", ""));
                        }
                        if (dimension.ElementoMiembroTipificado != null)
                        {
                            tipoDimension += string.Format(ConstBlockStoreHechos.DimensionMiembroTipificado, string.IsNullOrEmpty(dimension.ElementoMiembroTipificado) ? WebUtility.HtmlEncode(dimension.ElementoMiembroTipificado) : string.Empty);
                        }

                        if (dimension.etiquetasDimension != null)
                        {
                            var estructuraEtiqueta = dimension.etiquetasDimension.Aggregate(string.Empty, (current, itemEtiqueta) => string.Format(ConstEstandar.AnidamientoTres, current, string.Format(ConstBlockStoreHechos.EstructuraEtiqueta, itemEtiqueta.lenguaje, itemEtiqueta.valor.Replace(ConstEstandar.ComillaSimple, string.Empty), itemEtiqueta.roll.Replace(ConstEstandar.ComillaSimple, string.Empty)), ConstEstandar.SeparadorComa));
                            var etiquetas          = string.Format(ConstBlockStoreHechos.ConceptoEtiquetaDimension, estructuraEtiqueta.Substring(0, estructuraEtiqueta.Length + ConstEstandar.MenosTres));
                            tipoDimension += etiquetas;
                        }

                        if (dimension.etiquetasMiembro != null)
                        {
                            var estructuraEtiqueta = dimension.etiquetasMiembro.Aggregate(string.Empty, (current, itemEtiqueta) => string.Format(ConstEstandar.AnidamientoTres, current, string.Format(ConstBlockStoreHechos.EstructuraEtiqueta, itemEtiqueta.lenguaje, itemEtiqueta.valor.Replace(ConstEstandar.ComillaSimple, string.Empty), itemEtiqueta.roll.Replace(ConstEstandar.ComillaSimple, string.Empty)), ConstEstandar.SeparadorComa));
                            var etiquetas          = string.Format(ConstBlockStoreHechos.ConceptoEtiquetaMiembroDimension, estructuraEtiqueta.Substring(0, estructuraEtiqueta.Length + ConstEstandar.MenosTres));
                            tipoDimension += etiquetas;
                        }


                        tipoDimension += ConstBlockStore.miCierreLlaveComa;
                    }

                    tipoDimension = string.Format(ConstEstandar.AnidamientoDos, tipoDimension.Substring(0, tipoDimension.Length + ConstEstandar.MenosUno), ConstEstandar.CierreCorchete);
                    elemento     += tipoDimension;
                }


                elemento += ConstEstandar.CierreLlave;

                blockStoreDocumentosyFiltros.registroBlockStore.Add(BsonDocument.Parse(elemento));
                blockStoreDocumentosyFiltros.filtrosBlockStore.Add(BsonDocument.Parse("{'codigoHashRegistro':'" + itemEstructuraInstancia.codigoHashRegistro + "'}"));


                listadoDocumentos.Add(blockStoreDocumentosyFiltros);
            }


            return(listadoDocumentos);
        }
Ejemplo n.º 2
0
        public JsonResult Add()
        {
            var files = HttpContext.Current.Request.Files;

            // 校验上传文件
            if (files.Count != 1 || !files[0].FileName.EndsWith(".ttf"))
            {
                return(Json(new Result
                {
                    Code = 300,
                    Msg = "Only font file (.ttf) is allowed to upload."
                }));
            }

            var file     = files[0];
            var fileName = file.FileName;

            // 保存文件
            var now = DateTime.Now;

            var savePath     = $"/Upload/Font/{now.ToString("yyyyMMddHHmmss")}";
            var physicalPath = HttpContext.Current.Server.MapPath(savePath);

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

            // 判断文件是否存在
            if (File.Exists($"{physicalPath}\\{fileName}"))
            {
                return(Json(new Result
                {
                    Code = 300,
                    Msg = "The file is already existed."
                }));
            }

            file.SaveAs($"{physicalPath}\\{fileName}");

            // 保存到Mongo
            var fileSize           = file.ContentLength;
            var fileType           = file.ContentType;
            var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);

            var pinyin = PinYinHelper.GetTotalPinYin(fileNameWithoutExt);

            var mongo = new MongoHelper();

            var doc = new BsonDocument
            {
                ["ID"]          = ObjectId.GenerateNewId(),
                ["Name"]        = fileNameWithoutExt,
                ["TotalPinYin"] = string.Join("", pinyin.TotalPinYin),
                ["FirstPinYin"] = string.Join("", pinyin.FirstPinYin),
                ["Url"]         = $"{savePath}/{fileName}",
                ["CreateTime"]  = BsonDateTime.Create(now),
            };

            mongo.InsertOne(Constant.TypefaceCollectionName, doc);

            return(Json(new Result
            {
                Code = 200,
                Msg = "Upload successfully!"
            }));
        }
Ejemplo n.º 3
0
        public static void Seed(IDbContext IdbContext)
        {
            var dbContext = IdbContext;

            if (dbContext != null)
            {
                var collection = dbContext.Database.GetCollection <KeyResultArea>($"{nameof(KeyResultArea)}s");
                if (!collection.AsQueryable().Any())
                {
                    var dataToAdd = new List <KeyResultArea>()
                    {
                        new KeyResultArea
                        {
                            UserId           = Guid.NewGuid().ToString(),
                            EmployeeId       = 1,
                            AppraiserDetails = new NameEmail {
                                Name = "Emmanuel", EmployeeId = 1, Email = "*****@*****.**"
                            },
                            HodDetails = new NameEmail {
                                Name = "EmmanuelHod", EmployeeId = 4, Email = "*****@*****.**"
                            },
                            keyOutcomes = new List <KeyOutcome>()
                            {
                                new KeyOutcome {
                                    Question = "Test question 1", TimeLimit = BsonDateTime.Create(DateTime.Now.AddDays(-20)).ToString()
                                },
                                new KeyOutcome {
                                    Question = "Test question 2", TimeLimit = BsonDateTime.Create(DateTime.Now.AddDays(-20)).ToString()
                                },
                                new KeyOutcome {
                                    Question = "Test question 3", TimeLimit = BsonDateTime.Create(DateTime.Now).ToString()
                                },
                            },
                            Weight   = 50,
                            Approved = true,
                            Name     = "School Manager",
                            Status   = new ApprovalStatus  {
                                Employee = true, Hod = true, IsAccepted = true
                            }
                        },
                        new KeyResultArea
                        {
                            UserId           = Guid.NewGuid().ToString(),
                            EmployeeId       = 1,
                            AppraiserDetails = new NameEmail {
                                Name = "Test", EmployeeId = 1, Email = "*****@*****.**"
                            },
                            HodDetails = new NameEmail {
                                Name = "TestlHod", EmployeeId = 1, Email = "*****@*****.**"
                            },
                            keyOutcomes = new List <KeyOutcome>()
                            {
                                new KeyOutcome {
                                    Question = "Test question 4", TimeLimit = "Continous"
                                },
                                new KeyOutcome {
                                    Question = "Test question 5", TimeLimit = "Continous"
                                },
                                new KeyOutcome {
                                    Question = "Test question 6", TimeLimit = "Continous"
                                },
                            },
                            Weight   = 50,
                            Approved = true,
                            Name     = "School Manager",
                            Status   = new ApprovalStatus {
                                Employee = true, Hod = true, IsAccepted = true
                            }
                        }
                    };

                    collection.InsertMany(dataToAdd);
                }

                var coreValueCollection = dbContext.Database.GetCollection <CoreValuesKRA>($"{nameof(CoreValuesKRA)}s");
                if (!coreValueCollection.AsQueryable().Any())
                {
                    var data = new List <CoreValuesKRA>()
                    {
                        new CoreValuesKRA()
                        {
                            Name        = "Tenece Core Value",
                            Description = "5% of total appraisal score, Kindly select this if you are in tenece",
                            Weight      = 5,
                            keyOutcomes =
                            {
                                new KeyOutcome()
                                {
                                    Question = "Innovation and Creativity - Designs/Changes process/work to improve/increase value to self, organization and customer.", TimeLimit = "Ongoing"
                                },
                                new KeyOutcome()
                                {
                                    Question = "Building best people - Learns, share knowledge with others and implements learning in the course of work.", TimeLimit = "Ongoing"
                                },
                                new KeyOutcome()
                                {
                                    Question = "Value-oriented leadership - Objectively guiding and inspiring self and others for better outcome while managing different concerns.", TimeLimit = "Ongoing"
                                },
                                new KeyOutcome()
                                {
                                    Question = "Customer focus - Directly and indirectly brings value to customer.", TimeLimit = "Ongoing"
                                },
                                new KeyOutcome()
                                {
                                    Question = "Entrepreneurship - Proposes additional task for company profit purposes. Carries out tasks while considering risk and quality for organizational profit.", TimeLimit = "Ongoing"
                                },
                                new KeyOutcome()
                                {
                                    Question = "Action - Carries out tasks wwith confidence to achieve results, humility to take lessons from mistakes and make required corrections.", TimeLimit = "Ongoing"
                                },
                                new KeyOutcome()
                                {
                                    Question = "Specialization - Expresses deep knowledge and meets expected performance in a subject matter.", TimeLimit = "Ongoing"
                                },
                                new KeyOutcome()
                                {
                                    Question = "Dynamism - Progressively delivers standard results with energy.", TimeLimit = "Ongoing"
                                },
                                new KeyOutcome()
                                {
                                    Question = "Candor - Expresses self with respect for others/authority, while remaining open and honest.", TimeLimit = "Ongoing"
                                },
                                new KeyOutcome()
                                {
                                    Question = "Keep it simple - Encourages clarity and simplicity in communication and work delivery.", TimeLimit = "Ongoing"
                                },
                                new KeyOutcome()
                                {
                                    Question = "Innovation and Creativity - Designs/Changes process/work to improve/increase value to self, organization and customer.", TimeLimit = "Ongoing"
                                },
                            },
                            Approved = true,
                            IsActive = true
                        },
                        new CoreValuesKRA()
                        {
                            Name        = "Genesys Core Values",
                            Description = "10% of total appraisal score",
                            Weight      = 10,
                            keyOutcomes =
                            {
                                new KeyOutcome()
                                {
                                    Question = "Passion - Approaches work with positivity, optimism, enthusiasm and belief", TimeLimit = "Ongoing"
                                },
                                new KeyOutcome()
                                {
                                    Question = "Excellence - Delivers top quality work with little supervision in record time while constantly exploring opportunities for growth and improvement", TimeLimit = "Ongoing"
                                },
                                new KeyOutcome()
                                {
                                    Question = "Collaboration - Works well with team mates, finds and shares knowledge to propel the team to success", TimeLimit = "Ongoing"
                                },
                                new KeyOutcome()
                                {
                                    Question = "Candor - Expresses self with respect for others/authority, while remaining open and honest.", TimeLimit = "Ongoing"
                                },
                            },
                            Approved = true,
                            IsActive = true
                        }
                    };

                    coreValueCollection.InsertMany(data);
                }

                SeedAppraisalConfig(dbContext);
            }
        }
Ejemplo n.º 4
0
        public JsonResult Save(PrefabSaveModel model)
        {
            var objectId = ObjectId.GenerateNewId();

            if (!string.IsNullOrEmpty(model.ID) && !ObjectId.TryParse(model.ID, out objectId))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "ID is not allowed."
                }));
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Name is not allowed to be empty."
                }));
            }

            // 查询
            var mongo  = new MongoHelper();
            var filter = Builders <BsonDocument> .Filter.Eq("ID", objectId);

            var doc = mongo.FindOne(Constant.PrefabCollectionName, filter);

            var now = DateTime.Now;

            if (doc == null) // 新建
            {
                var pinyin = PinYinHelper.GetTotalPinYin(model.Name);

                doc = new BsonDocument
                {
                    ["ID"]           = objectId,
                    ["Name"]         = model.Name,
                    ["CategoryID"]   = 0,
                    ["CategoryName"] = "",
                    ["TotalPinYin"]  = string.Join("", pinyin.TotalPinYin),
                    ["FirstPinYin"]  = string.Join("", pinyin.FirstPinYin),
                    ["Version"]      = 0,
                    ["CreateTime"]   = BsonDateTime.Create(now),
                    ["UpdateTime"]   = BsonDateTime.Create(now),
                    ["Data"]         = BsonDocument.Parse(model.Data),
                    ["Thumbnail"]    = ""
                };

                if (ConfigHelper.EnableAuthority)
                {
                    var user = UserHelper.GetCurrentUser();

                    if (user != null)
                    {
                        doc["UserID"] = user.ID;
                    }
                }

                mongo.InsertOne(Constant.PrefabCollectionName, doc);
            }
            else // 更新
            {
                var update1 = Builders <BsonDocument> .Update.Set("UpdateTime", BsonDateTime.Create(now));

                var update2 = Builders <BsonDocument> .Update.Set("Data", BsonDocument.Parse(model.Data));

                var update = Builders <BsonDocument> .Update.Combine(update1, update2);

                mongo.UpdateOne(Constant.PrefabCollectionName, filter, update);
            }

            return(Json(new
            {
                Code = 200,
                Msg = "Saved successfully!",
                ID = objectId
            }));
        }
Ejemplo n.º 5
0
        public JsonResult Upload()
        {
            var Request = HttpContext.Current.Request;
            var Server  = HttpContext.Current.Server;

            if (Request.Files.Count == 0)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Please select an file."
                }));
            }

            // 文件信息
            var file               = Request.Files[0];
            var fileName           = file.FileName;
            var fileSize           = file.ContentLength;
            var fileType           = file.ContentType;
            var fileExt            = Path.GetExtension(fileName).ToLower();
            var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);

            if (fileExt != ".jpg" && fileExt != ".jpeg" && fileExt != ".png" && fileExt != ".gif")
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Only jpg, png, gif format is allowed to upload!"
                }));
            }

            // 上传文件
            var now = DateTime.Now;

            var savePath     = $"/Upload/File/{now.ToString("yyyyMMddHHmmss")}";
            var physicalPath = Server.MapPath(savePath);

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

            file.SaveAs($"{physicalPath}\\{fileName}");

            // 保存Mongo
            var pinyin = PinYinHelper.GetTotalPinYin(fileNameWithoutExt);

            var mongo = new MongoHelper();

            var doc = new BsonDocument
            {
                ["AddTime"]     = BsonDateTime.Create(now),
                ["FileName"]    = fileName,
                ["FileSize"]    = fileSize,
                ["FileType"]    = fileType,
                ["FirstPinYin"] = string.Join("", pinyin.FirstPinYin),
                ["Name"]        = fileNameWithoutExt,
                ["SaveName"]    = fileName,
                ["SavePath"]    = savePath,
                ["Thumbnail"]   = "",
                ["TotalPinYin"] = string.Join("", pinyin.TotalPinYin),
                ["Url"]         = $"{savePath}/{fileName}"
            };

            if (ConfigHelper.EnableAuthority)
            {
                var user = UserHelper.GetCurrentUser();

                if (user != null)
                {
                    doc["UserID"] = user.ID;
                }
            }

            mongo.InsertOne(Constant.FileCollectionName, doc);

            return(Json(new
            {
                Code = 200,
                Msg = "Upload successfully!",
                Data = new
                {
                    fileName,
                    fileSize,
                    fileType,
                    url = $"{savePath}/{fileName}"
                }
            }));
        }
Ejemplo n.º 6
0
        public JsonResult Add()
        {
            var files = HttpContext.Current.Request.Files;

            // 校验上传文件
            if (files.Count != 1)
            {
                return(Json(new Result
                {
                    Code = 300,
                    Msg = "Only one or six files is allowed to upload!"
                }));
            }

            var file     = files[0];
            var fileName = file.FileName;
            var fileExt  = Path.GetExtension(fileName);

            if (fileExt == null || fileExt.ToLower() != ".mp4" && fileExt.ToLower() != ".webm")
            {
                return(Json(new Result
                {
                    Code = 300,
                    Msg = "Only mp4 or webm format is allowed to upload!"
                }));
            }

            // 保存文件
            var now = DateTime.Now;

            var savePath     = $"/Upload/Video/{now.ToString("yyyyMMddHHmmss")}";
            var physicalPath = HttpContext.Current.Server.MapPath(savePath);

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

            file.SaveAs($"{physicalPath}\\{fileName}");

            // 保存到Mongo
            var fileSize           = file.ContentLength;
            var fileType           = file.ContentType;
            var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);

            var pinyin = PinYinHelper.GetTotalPinYin(fileNameWithoutExt);

            var mongo = new MongoHelper();

            var doc = new BsonDocument
            {
                ["ID"]          = ObjectId.GenerateNewId(),
                ["AddTime"]     = BsonDateTime.Create(now),
                ["FileName"]    = fileName,
                ["FileSize"]    = fileSize,
                ["FileType"]    = fileType,
                ["FirstPinYin"] = string.Join("", pinyin.FirstPinYin),
                ["TotalPinYin"] = string.Join("", pinyin.TotalPinYin),
                ["Name"]        = fileNameWithoutExt,
                ["SaveName"]    = fileName,
                ["SavePath"]    = savePath,
                ["Url"]         = $"{savePath}/{fileName}",
                ["Thumbnail"]   = "", // TODO: 从视频获取截图
                ["CreateTime"]  = now,
                ["UpdateTime"]  = now,
            };

            mongo.InsertOne(Constant.VideoCollectionName, doc);

            return(Json(new Result
            {
                Code = 200,
                Msg = "Upload successfully!"
            }));
        }
Ejemplo n.º 7
0
        public JsonResult Save(SaveSceneModel model)
        {
            var objectId = ObjectId.GenerateNewId();

            if (!string.IsNullOrEmpty(model.ID) && !ObjectId.TryParse(model.ID, out objectId))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "场景ID不合法。"
                }));
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "场景名称不允许为空。"
                }));
            }

            if (model.Name.StartsWith("_"))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "场景名称不允许以下划线开头。"
                }));
            }

            // 查询场景信息
            var mongo  = new MongoHelper();
            var filter = Builders <BsonDocument> .Filter.Eq("ID", objectId);

            var doc = mongo.FindOne(Constant.SceneCollectionName, filter);

            var now = DateTime.Now;

            string collectionName;

            if (doc == null) // 新建场景
            {
                collectionName = "Scene" + now.ToString("yyyyMMddHHmmss");
            }
            else // 编辑场景
            {
                collectionName = doc["CollectionName"].ToString();
            }

            // 保存或更新场景综合信息
            if (doc == null)
            {
                var pinyin = PinYinHelper.GetTotalPinYin(model.Name);

                doc                   = new BsonDocument();
                doc["ID"]             = objectId;
                doc["Name"]           = model.Name;
                doc["TotalPinYin"]    = string.Join("", pinyin.TotalPinYin);
                doc["FirstPinYin"]    = string.Join("", pinyin.FirstPinYin);
                doc["CollectionName"] = collectionName;
                doc["Version"]        = 0;
                doc["CreateTime"]     = BsonDateTime.Create(now);
                doc["UpdateTime"]     = BsonDateTime.Create(now);
                mongo.InsertOne(Constant.SceneCollectionName, doc);
            }
            else
            {
                var update1 = Builders <BsonDocument> .Update.Set("Version", int.Parse(doc["Version"].ToString()) + 1);

                var update2 = Builders <BsonDocument> .Update.Set("UpdateTime", BsonDateTime.Create(now));

                var update = Builders <BsonDocument> .Update.Combine(update1, update2);

                mongo.UpdateOne(Constant.SceneCollectionName, filter, update);
            }

            // 保存场景信息
            var list = JsonHelper.ToObject <JArray>(model.Data);

            var docs = new List <BsonDocument>();

            foreach (var i in list)
            {
                docs.Add(BsonDocument.Parse(i.ToString()));
            }

            mongo.DeleteAll(collectionName);
            mongo.InsertMany(collectionName, docs);

            return(Json(new
            {
                Code = 200,
                Msg = "保存成功!",
                ID = objectId
            }));
        }
Ejemplo n.º 8
0
        public JsonResult Add()
        {
            var Request = HttpContext.Current.Request;
            var Server  = HttpContext.Current.Server;

            // 文件信息
            var file               = Request.Files[0];
            var fileName           = file.FileName;
            var fileSize           = file.ContentLength;
            var fileType           = file.ContentType;
            var fileExt            = Path.GetExtension(fileName);
            var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);

            if (fileExt == null || fileExt.ToLower() != ".zip")
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Only zip file is allowed!"
                }));
            }

            // 保存文件
            var now = DateTime.Now;

            var savePath     = $"/Upload/Model/{now.ToString("yyyyMMddHHmmss")}";
            var physicalPath = Server.MapPath(savePath);

            var tempPath = physicalPath + "\\temp"; // zip压缩文件临时保存目录

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

            file.SaveAs($"{tempPath}\\{fileName}");

            // 解压文件
            ZipHelper.Unzip($"{tempPath}\\{fileName}", physicalPath);

            // 删除临时目录
            Directory.Delete(tempPath, true);

            // 判断文件类型
            string entryFileName = null;
            var    meshType      = MeshType.unknown;

            var files = Directory.GetFiles(physicalPath);

            if (files.Where(o => o.ToLower().EndsWith(".3ds")).Count() > 0) // 3ds文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".3ds")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType._3ds;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".3mf")).Count() > 0) // 3mf文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".3mf")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType._3mf;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".amf")).Count() > 0) // amf文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".amf")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.amf;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".assimp")).Count() > 0) // assimp文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".assimp")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.assimp;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".json")).Count() > 0 && files.Where(o => o.ToLower().EndsWith(".bin")).Count() > 0) // binary文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".json")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.binary;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".json")).Count() > 0) // json文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".json")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.json;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".js")).Count() > 0) // Skinned json文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".js")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.js;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".awd")).Count() > 0) // awd文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".awd")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.awd;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".babylon")).Count() > 0) // babylon文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".babylon")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.babylon;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".bvh")).Count() > 0) // bvh文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".bvh")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.bvh;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".ctm")).Count() > 0) // ctm文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".ctm")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.ctm;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".dae")).Count() > 0) // dae文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".dae")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.dae;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".drc")).Count() > 0) // drc文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".drc")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.drc;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".fbx")).Count() > 0) // fbx文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".fbx")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.fbx;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".gcode")).Count() > 0) // gcode文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".gcode")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.gcode;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".glb")).Count() > 0) // glb文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".glb")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.glb;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".gltf")).Count() > 0) // gltf文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".gltf")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.gltf;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".kmz")).Count() > 0) // kmz文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".kmz")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.kmz;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".md2")).Count() > 0) // md2文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".md2")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.md2;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".nrrd")).Count() > 0) // nrrd文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".nrrd")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.nrrd;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".obj")).Count() > 0) // obj文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".obj")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.obj;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".pcd")).Count() > 0) // pcd文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".pcd")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.pcd;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".pdb")).Count() > 0) // pdb文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".pdb")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.pdb;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".ply")).Count() > 0) // ply文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".ply")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.ply;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".pmd")).Count() > 0) // pmd文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".pmd")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.pmd;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".pmx")).Count() > 0) // pmd文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".pmx")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.pmx;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".prwm")).Count() > 0) // prwm文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".prwm")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.prwm;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".sea")).Count() > 0) // sea3d文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".sea")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.sea3d;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".stl")).Count() > 0) // stl文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".stl")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.stl;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".vrm")).Count() > 0) // vrm文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".vrm")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.vrm;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".wrl")).Count() > 0) // vrml文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".wrl")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.vrml;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".vtk")).Count() > 0) // vtk文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".vtk")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.vtk;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".lmesh")).Count() > 0) // lol文件
            {
                if (files.Where(o => o.ToLower().EndsWith(".lanim")).Count() == -1)
                {
                    Directory.Delete(physicalPath, true);

                    return(Json(new
                    {
                        Code = 300,
                        Msg = "lanim file is not uploaded!"
                    }));
                }

                if (files.Where(o => o.ToLower().EndsWith(".png")).Count() == -1)
                {
                    Directory.Delete(physicalPath, true);

                    return(Json(new
                    {
                        Code = 300,
                        Msg = "png file is not uploaded!"
                    }));
                }

                var lmeshName    = files.Where(o => o.ToLower().EndsWith(".lmesh")).FirstOrDefault();
                var lanimName    = files.Where(o => o.ToLower().EndsWith(".lanim")).FirstOrDefault();
                var ltextureName = files.Where(o => o.ToLower().EndsWith(".png")).FirstOrDefault();

                lmeshName    = $"{savePath}/{Path.GetFileName(lmeshName)}";
                lanimName    = $"{savePath}/{Path.GetFileName(lanimName)}";
                ltextureName = $"{savePath}/{Path.GetFileName(ltextureName)}";

                entryFileName = $"{lmeshName};{lanimName};{ltextureName}";

                meshType = MeshType.lol;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".x")).Count() > 0) // x文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".x")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.x;
            }

            if (entryFileName == null || meshType == MeshType.unknown)
            {
                Directory.Delete(physicalPath, true);

                return(Json(new
                {
                    Code = 300,
                    Msg = "Unknown file type!"
                }));
            }

            var pinyin = PinYinHelper.GetTotalPinYin(fileNameWithoutExt);

            // 保存到Mongo
            var mongo = new MongoHelper();

            var doc = new BsonDocument
            {
                ["AddTime"]     = BsonDateTime.Create(now),
                ["FileName"]    = fileName,
                ["FileSize"]    = fileSize,
                ["FileType"]    = fileType,
                ["FirstPinYin"] = string.Join("", pinyin.FirstPinYin),
                ["Name"]        = fileNameWithoutExt,
                ["SaveName"]    = fileName,
                ["SavePath"]    = savePath,
                ["Thumbnail"]   = "",
                ["TotalPinYin"] = string.Join("", pinyin.TotalPinYin),
                ["Type"]        = meshType.ToString(),
                ["Url"]         = entryFileName
            };

            mongo.InsertOne(Constant.MeshCollectionName, doc);

            return(Json(new
            {
                Code = 200,
                Msg = "Upload successfully!"
            }));
        }
Ejemplo n.º 9
0
        public JsonResult Add()
        {
            var files = HttpContext.Current.Request.Files;

            // 校验上传文件
            if (files.Count != 1 && files.Count != 6)
            {
                return(Json(new Result
                {
                    Code = 300,
                    Msg = "只允许上传1个或6个文件!"
                }));
            }

            for (var i = 0; i < files.Count; i++)
            {
                var file1     = files[i];
                var fileName1 = file1.FileName;
                var fileExt1  = Path.GetExtension(fileName1);
                if (fileExt1 == null || fileExt1.ToLower() != ".jpg" && fileExt1.ToLower() != ".jpeg" && fileExt1.ToLower() != ".png" && fileExt1.ToLower() != ".gif" && fileExt1.ToLower() != ".mp4")
                {
                    return(Json(new Result
                    {
                        Code = 300,
                        Msg = "只允许上传jpg、png或mp4格式文件!"
                    }));
                }
            }

            // 保存文件
            var now = DateTime.Now;

            var savePath     = $"/Upload/Texture/{now.ToString("yyyyMMddHHmmss")}";
            var physicalPath = HttpContext.Current.Server.MapPath(savePath);

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

            for (var i = 0; i < files.Count; i++)
            {
                var file1     = files[i];
                var fileName1 = file1.FileName;

                file1.SaveAs($"{physicalPath}\\{fileName1}");
            }

            // 保存到Mongo
            // 立体贴图的情况,除Url外,所有信息取posX的信息即可。
            var file               = files[0];
            var fileName           = file.FileName;
            var fileSize           = file.ContentLength;
            var fileType           = file.ContentType;
            var fileExt            = Path.GetExtension(fileName);
            var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);

            var pinyin = PinYinHelper.GetTotalPinYin(fileNameWithoutExt);

            var mongo = new MongoHelper();

            var doc = new BsonDocument
            {
                ["ID"]          = ObjectId.GenerateNewId(),
                ["AddTime"]     = BsonDateTime.Create(now),
                ["FileName"]    = fileName,
                ["FileSize"]    = fileSize,
                ["FileType"]    = fileType,
                ["FirstPinYin"] = string.Join("", pinyin.FirstPinYin),
                ["Name"]        = fileNameWithoutExt,
                ["SaveName"]    = fileName,
                ["SavePath"]    = savePath
            };

            if (Path.GetExtension(files[0].FileName).ToLower() == ".mp4")
            {
                // TODO: 通过插件获取mp4缩略图
                doc["Thumbnail"] = $"";
            }
            else
            {
                doc["Thumbnail"] = $"{savePath}/{fileName}";
            }

            doc["TotalPinYin"] = string.Join("", pinyin.TotalPinYin);

            if (files.Count == 6) // 立体贴图
            {
                doc["Type"] = MapType.cube.ToString();

                var doc1 = new BsonDocument
                {
                    ["PosX"] = $"{savePath}/{files["posX"].FileName}",
                    ["NegX"] = $"{savePath}/{files["negX"].FileName}",
                    ["PosY"] = $"{savePath}/{files["posY"].FileName}",
                    ["NegY"] = $"{savePath}/{files["negY"].FileName}",
                    ["PosZ"] = $"{savePath}/{files["posZ"].FileName}",
                    ["NegZ"] = $"{savePath}/{files["negZ"].FileName}"
                };

                doc["Url"] = doc1;
            }
            else if (Path.GetExtension(files[0].FileName).ToLower() == ".mp4") // 视频贴图
            {
                doc["Type"] = MapType.video.ToString();
                doc["Url"]  = $"{savePath}/{fileName}";
            }
            else
            {
                doc["Type"] = MapType.unknown.ToString();
                doc["Url"]  = $"{savePath}/{fileName}";
            }

            doc["CreateTime"] = now;
            doc["UpdateTime"] = now;

            mongo.InsertOne(Constant.MapCollectionName, doc);

            return(Json(new Result
            {
                Code = 200,
                Msg = "上传成功!"
            }));
        }
Ejemplo n.º 10
0
 public override TEntity Update(TEntity entity)
 {
     entity.ModifyTime = BsonDateTime.Create(DateTime.Now).ToLocalTime();
     Collection.ReplaceOne(e => e.Id == entity.Id, entity);
     return(entity);
 }
Ejemplo n.º 11
0
        public JsonResult Add()
        {
            var file               = HttpContext.Current.Request.Files[0];
            var fileName           = file.FileName;
            var fileSize           = file.ContentLength;
            var fileType           = file.ContentType;
            var fileExt            = Path.GetExtension(fileName);
            var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);

            if (fileExt == null || fileExt.ToLower() != ".mp3" && fileExt.ToLower() != ".wav" && fileExt.ToLower() != ".ogg")
            {
                return(Json(new Result
                {
                    Code = 300,
                    Msg = "Only mp3, wav, ogg format is allowed!"
                }));
            }

            // 保存文件
            var now = DateTime.Now;

            var savePath     = $"/Upload/Audio/{now.ToString("yyyyMMddHHmmss")}";
            var physicalPath = HttpContext.Current.Server.MapPath(savePath);

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

            file.SaveAs($"{physicalPath}\\{fileName}");

            var pinyin = PinYinHelper.GetTotalPinYin(fileNameWithoutExt);

            // 保存到Mongo
            var mongo = new MongoHelper();

            var doc = new BsonDocument
            {
                ["ID"]          = ObjectId.GenerateNewId(),
                ["AddTime"]     = BsonDateTime.Create(now),
                ["FileName"]    = fileName,
                ["FileSize"]    = fileSize,
                ["FileType"]    = fileType,
                ["FirstPinYin"] = string.Join("", pinyin.FirstPinYin),
                ["Name"]        = fileNameWithoutExt,
                ["SaveName"]    = fileName,
                ["SavePath"]    = savePath,
                ["TotalPinYin"] = string.Join("", pinyin.TotalPinYin),
                ["Type"]        = AudioType.unknown.ToString(),
                ["Url"]         = $"{savePath}/{fileName}",
                ["CreateTime"]  = now,
                ["UpdateTime"]  = now
            };

            if (ConfigHelper.EnableAuthority)
            {
                var user = UserHelper.GetCurrentUser();

                if (user != null)
                {
                    doc["UserID"] = user.ID;
                }
            }

            mongo.InsertOne(Constant.AudioCollectionName, doc);

            return(Json(new Result
            {
                Code = 200,
                Msg = "Upload successfully!"
            }));
        }
Ejemplo n.º 12
0
        public JsonResult Upload()
        {
            var Request = HttpContext.Current.Request;
            var Server  = HttpContext.Current.Server;

            // 文件信息
            var file               = Request.Files[0];
            var fileName           = file.FileName;
            var fileSize           = file.ContentLength;
            var fileType           = file.ContentType;
            var fileExt            = Path.GetExtension(fileName).ToLower();
            var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);

            if (fileExt != ".jpg" && fileExt != ".jpeg" && fileExt != ".png" && fileExt != ".gif")
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "只允许上传图片!"
                }));
            }

            // 上传文件
            var now = DateTime.Now;

            var savePath     = $"/Upload/File/{now.ToString("yyyyMMddHHmmss")}";
            var physicalPath = Server.MapPath(savePath);

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

            file.SaveAs($"{physicalPath}\\{fileName}");

            // 保存Mongo
            var pinyin = PinYinHelper.GetTotalPinYin(fileNameWithoutExt);

            var mongo = new MongoHelper();

            var doc = new BsonDocument
            {
                ["AddTime"]     = BsonDateTime.Create(now),
                ["FileName"]    = fileName,
                ["FileSize"]    = fileSize,
                ["FileType"]    = fileType,
                ["FirstPinYin"] = string.Join("", pinyin.FirstPinYin),
                ["Name"]        = fileNameWithoutExt,
                ["SaveName"]    = fileName,
                ["SavePath"]    = savePath,
                ["Thumbnail"]   = "",
                ["TotalPinYin"] = string.Join("", pinyin.TotalPinYin),
                ["Url"]         = $"{savePath}/{fileName}"
            };

            mongo.InsertOne(Constant.FileCollectionName, doc);

            return(Json(new
            {
                Code = 200,
                Msg = "上传成功!",
                Data = new
                {
                    fileName,
                    fileSize,
                    fileType,
                    url = $"{savePath}/{fileName}"
                }
            }));
        }
Ejemplo n.º 13
0
        public void TestClassWithBsonValueId()
        {
            // repeats all tee TestClassWithBsonXyzId tests using ClassWithBsonValueId
            {
                // same as TestClassWithBonArrayId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = new BsonArray(), X = 1
                };
                Assert.Throws <MongoSafeModeException>(() => { _collection.Insert(doc); });

                doc = new ClassWithBsonValueId {
                    Id = new BsonArray {
                        1, 2, 3
                    }, X = 1
                };
                Assert.Throws <MongoSafeModeException>(() => { _collection.Insert(doc); });
            }

            {
                // same as TestClastWithBsonBinaryDataId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonBinaryData.Create(new byte[] { }), X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonBinaryData.Create(new byte[] { 1, 2, 3 }), X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonBooleanId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonBoolean.Create(false), X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonBoolean.Create(true), X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonDocumentId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = new BsonDocument(), X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = new BsonDocument {
                        { "A", 1 }, { "B", 2 }
                    }, X = 3
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonDateTimeId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonDateTime.Create(DateTime.MinValue), X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonDateTime.Create(DateTime.UtcNow), X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonDateTime.Create(DateTime.MaxValue), X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonDoubleId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonDouble.Create(0.0), X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonDouble.Create(1.0), X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonInt32Id
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonInt32.Create(0), X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonInt32.Create(1), X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonInt64Id
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonInt64.Create(0), X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonInt64.Create(1), X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonMaxKeyId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);
                Assert.AreEqual(null, doc.Id);

                doc = new ClassWithBsonValueId {
                    Id = BsonMaxKey.Value, X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonMinKeyId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);
                Assert.AreEqual(null, doc.Id);

                doc = new ClassWithBsonValueId {
                    Id = BsonMinKey.Value, X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonNullId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);
                Assert.AreEqual(null, doc.Id);

                doc = new ClassWithBsonValueId {
                    Id = BsonNull.Value, X = 1
                };
                Assert.Throws <MongoSafeModeException>(() => { _collection.Insert(doc); });
            }

            {
                // same as TestClassWithBsonObjectId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);
                Assert.IsNull(doc.Id); // BsonObjectIdGenerator is not invoked when nominalType is BsonValue

                doc = new ClassWithBsonValueId {
                    Id = BsonObjectId.Empty, X = 1
                };
                _collection.Insert(doc);
                Assert.AreEqual(ObjectId.Empty, doc.Id.AsObjectId); // BsonObjectIdGenerator is not invoked when nominalType is BsonValue

                doc = new ClassWithBsonValueId {
                    Id = BsonObjectId.GenerateNewId(), X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonStringId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);
                Assert.IsNull(doc.Id);

                doc = new ClassWithBsonValueId {
                    Id = "", X = 1
                };
                _collection.Insert(doc);
                Assert.AreEqual("", doc.Id.AsString);

                doc = new ClassWithBsonValueId {
                    Id = "123", X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonTimestampId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);
                Assert.IsNull(doc.Id);

                doc = new ClassWithBsonValueId {
                    Id = BsonTimestamp.Create(0, 0), X = 1
                };
                _collection.Insert(doc);
                Assert.AreEqual(BsonTimestamp.Create(0, 0), doc.Id);

                doc = new ClassWithBsonValueId {
                    Id = BsonTimestamp.Create(1, 2), X = 1
                };
                _collection.Insert(doc);
            }
        }
Ejemplo n.º 14
0
        public JsonResult Add()
        {
            var files = HttpContext.Current.Request.Files;

            // 校验上传文件
            if (files.Count != 1)
            {
                return(Json(new Result
                {
                    Code = 300,
                    Msg = "只允许上传1个文件!"
                }));
            }

            var file     = files[0];
            var fileName = file.FileName;
            var fileExt  = Path.GetExtension(fileName);

            if (fileExt == null || fileExt.ToLower() != ".jpg" && fileExt.ToLower() != ".jpeg" && fileExt.ToLower() != ".png" && fileExt.ToLower() != ".gif")
            {
                return(Json(new Result
                {
                    Code = 300,
                    Msg = "只允许上传jpg、png或gif格式文件!"
                }));
            }

            // 保存文件
            var now = DateTime.Now;

            var savePath     = $"/Upload/Screenshot/{now.ToString("yyyyMMddHHmmss")}";
            var physicalPath = HttpContext.Current.Server.MapPath(savePath);

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

            file.SaveAs($"{physicalPath}\\{fileName}");

            // 保存到Mongo
            var fileSize           = file.ContentLength;
            var fileType           = file.ContentType;
            var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);

            var pinyin = PinYinHelper.GetTotalPinYin(fileNameWithoutExt);

            var mongo = new MongoHelper();

            var doc = new BsonDocument
            {
                ["ID"]          = ObjectId.GenerateNewId(),
                ["AddTime"]     = BsonDateTime.Create(now),
                ["FileName"]    = fileName,
                ["FileSize"]    = fileSize,
                ["FileType"]    = fileType,
                ["FirstPinYin"] = string.Join("", pinyin.FirstPinYin),
                ["TotalPinYin"] = string.Join("", pinyin.TotalPinYin),
                ["Name"]        = fileNameWithoutExt,
                ["SaveName"]    = fileName,
                ["SavePath"]    = savePath,
                ["Url"]         = $"{savePath}/{fileName}",
                ["Thumbnail"]   = $"{savePath}/{fileName}",
                ["CreateTime"]  = now,
                ["UpdateTime"]  = now,
            };

            mongo.InsertOne(Constant.ScreenshotCollectionName, doc);

            return(Json(new Result
            {
                Code = 200,
                Msg = "上传成功!"
            }));
        }
Ejemplo n.º 15
0
        public JsonResult Add()
        {
            var Request = HttpContext.Current.Request;
            var Server  = HttpContext.Current.Server;

            // 文件信息
            var file               = Request.Files[0];
            var fileName           = file.FileName;
            var fileSize           = file.ContentLength;
            var fileType           = file.ContentType;
            var fileExt            = Path.GetExtension(fileName);
            var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);

            if (fileExt == null || fileExt.ToLower() != ".zip")
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Only zip file is allowed!"
                }));
            }

            // 保存文件
            var now = DateTime.Now;

            var savePath     = $"/Upload/Animation/{now.ToString("yyyyMMddHHmmss")}";
            var physicalPath = Server.MapPath(savePath);

            var tempPath = physicalPath + "\\temp"; // zip压缩文件临时保存目录

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

            file.SaveAs($"{tempPath}\\{fileName}");

            // 解压文件
            ZipHelper.Unzip($"{tempPath}\\{fileName}", physicalPath);

            // 删除临时目录
            Directory.Delete(tempPath, true);

            // 判断文件类型
            string entryFileName = null;
            var    animationType = AnimationType.unknown;

            var files = Directory.GetFiles(physicalPath);

            if (files.Where(o => o.ToLower().EndsWith(".vmd")).Count() > 0) // mmd动画文件或mmd相机动画文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".vmd")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                animationType = AnimationType.mmd;
            }

            if (entryFileName == null || animationType == AnimationType.unknown)
            {
                Directory.Delete(physicalPath, true);

                return(Json(new
                {
                    Code = 300,
                    Msg = "Unknown file type!"
                }));
            }

            var pinyin = PinYinHelper.GetTotalPinYin(fileNameWithoutExt);

            // 保存到Mongo
            var mongo = new MongoHelper();

            var doc = new BsonDocument
            {
                ["AddTime"]     = BsonDateTime.Create(now),
                ["FileName"]    = fileName,
                ["FileSize"]    = fileSize,
                ["FileType"]    = fileType,
                ["FirstPinYin"] = string.Join("", pinyin.FirstPinYin),
                ["Name"]        = fileNameWithoutExt,
                ["SaveName"]    = fileName,
                ["SavePath"]    = savePath,
                ["Thumbnail"]   = "",
                ["TotalPinYin"] = string.Join("", pinyin.TotalPinYin),
                ["Type"]        = animationType.ToString(),
                ["Url"]         = entryFileName
            };

            if (ConfigHelper.EnableAuthority)
            {
                var user = UserHelper.GetCurrentUser();

                if (user != null)
                {
                    doc["UserID"] = user.ID;
                }
            }

            mongo.InsertOne(Constant.AnimationCollectionName, doc);

            return(Json(new
            {
                Code = 200,
                Msg = "Upload successfully!"
            }));
        }
        /// <summary>
        /// Deserializes an object from a BsonReader.
        /// </summary>
        /// <param name="bsonReader">The BsonReader.</param>
        /// <param name="nominalType">The nominal type of the object.</param>
        /// <param name="actualType">The actual type of the object.</param>
        /// <param name="options">The serialization options.</param>
        /// <returns>An object.</returns>
        public override object Deserialize(
            BsonReader bsonReader,
            Type nominalType,
            Type actualType,
            IBsonSerializationOptions options
            )
        {
            VerifyTypes(nominalType, actualType, typeof(DateTime));

            var      dateTimeOptions = (options == null) ? DateTimeSerializationOptions.Defaults : (DateTimeSerializationOptions)options;
            DateTime value;

            var bsonType = bsonReader.CurrentBsonType;

            switch (bsonType)
            {
            case BsonType.DateTime:
                // use an intermediate BsonDateTime so MinValue and MaxValue are handled correctly
                value = BsonDateTime.Create(bsonReader.ReadDateTime()).Value;
                break;

            case BsonType.Document:
                bsonReader.ReadStartDocument();
                bsonReader.ReadDateTime("DateTime");     // ignore value (use Ticks instead)
                value = new DateTime(bsonReader.ReadInt64("Ticks"), DateTimeKind.Utc);
                bsonReader.ReadEndDocument();
                break;

            case BsonType.Int64:
                value = DateTime.SpecifyKind(new DateTime(bsonReader.ReadInt64()), DateTimeKind.Utc);
                break;

            case BsonType.String:
                // note: we're not using XmlConvert because of bugs in Mono
                if (dateTimeOptions.DateOnly)
                {
                    value = DateTime.SpecifyKind(DateTime.ParseExact(bsonReader.ReadString(), "yyyy-MM-dd", null), DateTimeKind.Utc);
                }
                else
                {
                    var formats = new string[] {
                        "yyyy-MM-ddK",
                        "yyyy-MM-ddTHH:mm:ssK",
                        "yyyy-MM-ddTHH:mm:ss.FFFFFFFK",
                    };
                    value = DateTime.ParseExact(bsonReader.ReadString(), formats, null, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);
                }
                break;

            default:
                var message = string.Format("Cannot deserialize DateTime from BsonType {0}.", bsonType);
                throw new FileFormatException(message);
            }

            if (dateTimeOptions.DateOnly)
            {
                if (value.TimeOfDay != TimeSpan.Zero)
                {
                    throw new FileFormatException("TimeOfDay component for DateOnly DateTime value is not zero.");
                }
                value = DateTime.SpecifyKind(value, dateTimeOptions.Kind); // not ToLocalTime or ToUniversalTime!
            }
            else
            {
                switch (dateTimeOptions.Kind)
                {
                case DateTimeKind.Local:
                case DateTimeKind.Unspecified:
                    value = BsonUtils.ToLocalTime(value, dateTimeOptions.Kind);
                    break;

                case DateTimeKind.Utc:
                    value = BsonUtils.ToUniversalTime(value);
                    break;
                }
            }

            return(value);
        }
Ejemplo n.º 17
0
        public JsonResult Save(SceneSaveModel model)
        {
            var objectId = ObjectId.GenerateNewId();

            if (!string.IsNullOrEmpty(model.ID) && !ObjectId.TryParse(model.ID, out objectId))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "ID is not allowed."
                }));
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Name is not allowed to be empty."
                }));
            }

            if (model.Name.StartsWith("_"))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Name is not allowed to start with _."
                }));
            }

            // 查询场景信息
            var mongo  = new MongoHelper();
            var filter = Builders <BsonDocument> .Filter.Eq("ID", objectId);

            var doc = mongo.FindOne(Constant.SceneCollectionName, filter);

            var now = DateTime.Now;

            string collectionName;
            var    version = -1;

            if (doc == null) // 新建场景
            {
                collectionName = "Scene" + now.ToString("yyyyMMddHHmmss");
                version        = 0;
            }
            else // 编辑场景
            {
                collectionName = doc["CollectionName"].ToString();
                version        = doc.Contains("Version") ? int.Parse(doc["Version"].ToString()) : 0;
                version++;
            }

            // 保存或更新场景综合信息
            if (doc == null)
            {
                var pinyin = PinYinHelper.GetTotalPinYin(model.Name);

                doc = new BsonDocument
                {
                    ["ID"]             = objectId,
                    ["Name"]           = model.Name,
                    ["TotalPinYin"]    = string.Join("", pinyin.TotalPinYin),
                    ["FirstPinYin"]    = string.Join("", pinyin.FirstPinYin),
                    ["CollectionName"] = collectionName,
                    ["Version"]        = version,
                    ["CreateTime"]     = BsonDateTime.Create(now),
                    ["UpdateTime"]     = BsonDateTime.Create(now),
                    ["IsPublic"]       = false,
                };

                if (ConfigHelper.EnableAuthority)
                {
                    var user = UserHelper.GetCurrentUser();

                    if (user != null)
                    {
                        doc["UserID"] = user.ID;
                    }
                }

                mongo.InsertOne(Constant.SceneCollectionName, doc);
            }
            else
            {
                var update1 = Builders <BsonDocument> .Update.Set("Version", version);

                var update2 = Builders <BsonDocument> .Update.Set("UpdateTime", BsonDateTime.Create(now));

                var update = Builders <BsonDocument> .Update.Combine(update1, update2);

                mongo.UpdateOne(Constant.SceneCollectionName, filter, update);

                // 将当前场景移入历史表
                var old = mongo.FindAll(collectionName).ToList();

                foreach (var i in old)
                {
                    i[Constant.VersionField] = version - 1;
                }

                if (old.Count > 0)
                {
                    // 移除_id,避免移入历史表时重复
                    for (var i = 0; i < old.Count; i++)
                    {
                        old[i].Remove("_id");
                    }

                    mongo.InsertMany($"{collectionName}{Constant.HistorySuffix}", old);
                }
            }

            // 保存新的场景信息
            var list = JsonHelper.ToObject <JArray>(model.Data);

            var docs = new List <BsonDocument>();

            foreach (var i in list)
            {
                docs.Add(BsonDocument.Parse(i.ToString()));
            }

            mongo.DeleteAll(collectionName);
            mongo.InsertMany(collectionName, docs);

            return(Json(new
            {
                Code = 200,
                Msg = "Saved successfully!",
                ID = objectId
            }));
        }
Ejemplo n.º 18
0
        // This process monitor and updates redundancy control of the driver instance in mongodb
        static async void ProcessRedundancyMongo(JSONSCADAConfig jsConfig)
        {
            do
            {
                try
                {
                    var lastActiveNodeKeepAliveTimeTag = DateTime.MinValue;
                    var countKeepAliveUpdates          = 0;
                    var countKeepAliveUpdatesLimit     = 4;
                    var Client = ConnectMongoClient(jsConfig);
                    var DB     = Client.GetDatabase(jsConfig.mongoDatabaseName);

                    // read and process instances configuration
                    var collinsts =
                        DB
                        .GetCollection
                        <protocolDriverInstancesClass
                        >(ProtocolDriverInstancesCollectionName);
                    do
                    {
                        bool isMongoLive =
                            DB
                            .RunCommandAsync((Command <BsonDocument>)
                                             "{ping:1}")
                            .Wait(1000);
                        if (!isMongoLive)
                        {
                            throw new Exception("Error on MongoDB connection ");
                        }

                        var collconns =
                            DB
                            .GetCollection
                            <OPCUA_connection
                            >(ProtocolConnectionsCollectionName);
                        var instances =
                            collinsts
                            .Find(inst =>
                                  inst.protocolDriver == ProtocolDriverName &&
                                  inst.protocolDriverInstanceNumber == ProtocolDriverInstanceNumber)
                            .ToList();
                        var foundinstance = false;
                        foreach (protocolDriverInstancesClass inst in instances)
                        {
                            foundinstance = true;

                            var nodefound = false;
                            foreach (var name in inst.nodeNames)
                            {
                                if (JSConfig.nodeName == name)
                                {
                                    nodefound = true;
                                }
                            }
                            if (!nodefound)
                            {
                                Log("Node '" +
                                    JSConfig.nodeName +
                                    "' not found in instances configuration!");
                                Environment.Exit(-1);
                            }

                            if (inst.activeNodeName == JSConfig.nodeName)
                            {
                                if (!Active) // will go active
                                {
                                    Log("Redundancy - ACTIVATING this Node!");
                                }
                                Active = true;
                                countKeepAliveUpdates = 0;
                            }
                            else
                            {
                                if (Active) // will go inactive
                                {           // wait a random time
                                    Log("Redundancy - DEACTIVATING this Node (other node active)!");
                                    countKeepAliveUpdates = 0;
                                    Random rnd = new Random();
                                    await Task.Delay(rnd.Next(1000, 5000));
                                }
                                Active = false;
                                if (lastActiveNodeKeepAliveTimeTag == inst.activeNodeKeepAliveTimeTag)
                                {
                                    countKeepAliveUpdates++;
                                }
                                lastActiveNodeKeepAliveTimeTag = inst.activeNodeKeepAliveTimeTag;
                                if (countKeepAliveUpdates > countKeepAliveUpdatesLimit)
                                { // time exceeded, be active
                                    Log("Redundancy - ACTIVATING this Node!");
                                    Active = true;
                                }
                            }

                            if (Active)
                            {
                                Log("Redundancy - This node is active.");

                                // update keep alive time
                                var filter1 =
                                    Builders <protocolDriverInstancesClass>
                                    .Filter
                                    .Eq(m => m.protocolDriver,
                                        ProtocolDriverName);

                                var filter2 =
                                    Builders <protocolDriverInstancesClass>
                                    .Filter
                                    .Eq(m => m.protocolDriverInstanceNumber,
                                        ProtocolDriverInstanceNumber);

                                var filter =
                                    Builders <protocolDriverInstancesClass>
                                    .Filter
                                    .And(filter1, filter2);

                                var update =
                                    Builders <protocolDriverInstancesClass>
                                    .Update
                                    .Set(m => m.activeNodeName, JSConfig.nodeName)
                                    .Set(m => m.activeNodeKeepAliveTimeTag, DateTime.Now);

                                var options =
                                    new FindOneAndUpdateOptions <protocolDriverInstancesClass, protocolDriverInstancesClass
                                                                 >();
                                options.IsUpsert = false;
                                await collinsts
                                .FindOneAndUpdateAsync(filter, update, options);

                                // update statistics for connections
                                foreach (OPCUA_connection srv in OPCUAconns)
                                {
                                    if (!(srv.connection is null))
                                    {
                                        // var stats = srv.connection.GetStatistics();
                                        var filt =
                                            new BsonDocument(new BsonDocument("protocolConnectionNumber",
                                                                              srv.protocolConnectionNumber));
                                        var upd =
                                            new BsonDocument("$set", new BsonDocument {
                                            { "stats", new BsonDocument {
                                                  { "nodeName", JSConfig.nodeName },
                                                  { "timeTag", BsonDateTime.Create(DateTime.Now) },
                                              } },
                                        });
                                        var res = collconns.UpdateOneAsync(filt, upd);
                                    }
                                }
                            }
                            else
                            {
                                if (inst.activeNodeName != "")
                                {
                                    Log("Redundancy - This node is INACTIVE! Node '" + inst.activeNodeName + "' is active, wait...");
                                }
                                else
                                {
                                    Log("Redundancy - This node is INACTIVE! No node is active, wait...");
                                }
                            }

                            break; // process just first result
                        }

                        if (!foundinstance)
                        {
                            if (Active) // will go inactive
                            {           // wait a random time
                                Log("Redundancy - DEACTIVATING this Node (no instance found)!");
                                countKeepAliveUpdates = 0;
                                Random rnd = new Random();
                                await Task.Delay(rnd.Next(1000, 5000));
                            }
                            Active = false;
                        }

                        await Task.Delay(5000);
                    }while (true);
                }
                catch (Exception e)
                {
                    Log("Exception Mongo");
                    Log(e);
                    Log(e
                        .ToString()
                        .Substring(0,
                                   e.ToString().IndexOf(Environment.NewLine)));
                    await Task.Delay(3000);
                }
            }while (true);
        }
Ejemplo n.º 19
0
        public Result Save(HttpContext context)
        {
            var Request = context.Request;
            var Server  = context.Server;

            // 文件信息
            var file               = Request.Files[0];
            var fileName           = file.FileName;
            var fileSize           = file.ContentLength;
            var fileType           = file.ContentType;
            var fileExt            = Path.GetExtension(fileName);
            var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);

            if (fileExt == null || fileExt.ToLower() != ".zip")
            {
                return(new Result
                {
                    Code = 300,
                    Msg = "只允许上传zip格式文件!"
                });
            }

            // 保存文件
            var now = DateTime.Now;

            var savePath     = $"/Upload/Model/{now.ToString("yyyyMMddHHmmss")}";
            var physicalPath = Server.MapPath(savePath);

            var tempPath = physicalPath + "\\temp"; // zip压缩文件临时保存目录

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

            file.SaveAs($"{tempPath}\\{fileName}");

            // 解压文件
            ZipHelper.Unzip($"{tempPath}\\{fileName}", physicalPath);

            // 删除临时目录
            Directory.Delete(tempPath, true);

            // 判断文件类型
            string entryFileName = null;
            var    meshType      = MeshType.unknown;

            var files = Directory.GetFiles(physicalPath);

            if (files.Where(o => o.ToLower().EndsWith(".amf")).Count() > 0) // amf文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".amf")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.amf;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".json")).Count() > 0 && files.Where(o => o.ToLower().EndsWith(".bin")).Count() > 0) // binary文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".json")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.binary;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".json")).Count() > 0) // json文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".json")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.json;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".js")).Count() > 0) // Skinned json文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".js")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.js;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".awd")).Count() > 0) // awd文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".awd")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.awd;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".babylon")).Count() > 0) // babylon文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".babylon")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.babylon;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".ctm")).Count() > 0) // ctm文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".ctm")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.ctm;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".dae")).Count() > 0) // dae文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".dae")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.dae;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".fbx")).Count() > 0) // fbx文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".fbx")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.fbx;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".glb")).Count() > 0) // glb文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".glb")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.glb;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".gltf")).Count() > 0) // gltf文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".gltf")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.gltf;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".kmz")).Count() > 0) // kmz文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".kmz")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.kmz;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".md2")).Count() > 0) // md2文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".md2")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.md2;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".obj")).Count() > 0) // obj文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".obj")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.obj;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".ply")).Count() > 0) // ply文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".ply")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.ply;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".stl")).Count() > 0) // stl文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".stl")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.stl;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".vtk")).Count() > 0) // vtk文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".vtk")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.vtk;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".lmesh")).Count() > 0) // lol文件
            {
                if (files.Where(o => o.ToLower().EndsWith(".lanim")).Count() == -1)
                {
                    Directory.Delete(physicalPath, true);

                    return(new Result
                    {
                        Code = 300,
                        Msg = "未上传动画(.lanim)文件!"
                    });
                }

                if (files.Where(o => o.ToLower().EndsWith(".png")).Count() == -1)
                {
                    Directory.Delete(physicalPath, true);

                    return(new Result
                    {
                        Code = 300,
                        Msg = "未上传贴图(.png)文件!"
                    });
                }

                var lmeshName    = files.Where(o => o.ToLower().EndsWith(".lmesh")).FirstOrDefault();
                var lanimName    = files.Where(o => o.ToLower().EndsWith(".lanim")).FirstOrDefault();
                var ltextureName = files.Where(o => o.ToLower().EndsWith(".png")).FirstOrDefault();

                lmeshName    = $"{savePath}/{Path.GetFileName(lmeshName)}";
                lanimName    = $"{savePath}/{Path.GetFileName(lanimName)}";
                ltextureName = $"{savePath}/{Path.GetFileName(ltextureName)}";

                entryFileName = $"{lmeshName};{lanimName};{ltextureName}";

                meshType = MeshType.lol;
            }

            if (entryFileName == null || meshType == MeshType.unknown)
            {
                Directory.Delete(physicalPath, true);

                return(new Result
                {
                    Code = 300,
                    Msg = "未知文件类型!"
                });
            }

            var pinyin = PinYinHelper.GetTotalPinYin(fileNameWithoutExt);

            // 保存到Mongo
            var mongo = new MongoHelper();

            var doc = new BsonDocument();

            doc["AddTime"]     = BsonDateTime.Create(now);
            doc["FileName"]    = fileName;
            doc["FileSize"]    = fileSize;
            doc["FileType"]    = fileType;
            doc["FirstPinYin"] = string.Join("", pinyin.FirstPinYin);
            doc["Name"]        = fileNameWithoutExt;
            doc["SaveName"]    = fileName;
            doc["SavePath"]    = savePath;
            doc["Thumbnail"]   = "";
            doc["TotalPinYin"] = string.Join("", pinyin.TotalPinYin);
            doc["Type"]        = meshType.ToString();
            doc["Url"]         = entryFileName;

            mongo.InsertOne(Constant.MeshCollectionName, doc);

            return(new Result
            {
                Code = 200,
                Msg = "上传成功!"
            });
        }
Ejemplo n.º 20
0
        public JsonResult Save(MaterialSaveModel model)
        {
            var objectId = ObjectId.GenerateNewId();

            if (!string.IsNullOrEmpty(model.ID) && !ObjectId.TryParse(model.ID, out objectId))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "ID不合法。"
                }));
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "名称不允许为空。"
                }));
            }

            // 查询
            var mongo  = new MongoHelper();
            var filter = Builders <BsonDocument> .Filter.Eq("ID", objectId);

            var doc = mongo.FindOne(Constant.MaterialCollectionName, filter);

            var now = DateTime.Now;

            if (doc == null) // 新建
            {
                var pinyin = PinYinHelper.GetTotalPinYin(model.Name);

                doc = new BsonDocument
                {
                    ["ID"]           = objectId,
                    ["Name"]         = model.Name,
                    ["CategoryID"]   = 0,
                    ["CategoryName"] = "",
                    ["TotalPinYin"]  = string.Join("", pinyin.TotalPinYin),
                    ["FirstPinYin"]  = string.Join("", pinyin.FirstPinYin),
                    ["Version"]      = 0,
                    ["CreateTime"]   = BsonDateTime.Create(now),
                    ["UpdateTime"]   = BsonDateTime.Create(now),
                    ["Data"]         = BsonDocument.Parse(model.Data),
                    ["Thumbnail"]    = model.Thumbnail
                };
                mongo.InsertOne(Constant.MaterialCollectionName, doc);
            }
            else // 更新
            {
                var update1 = Builders <BsonDocument> .Update.Set("UpdateTime", BsonDateTime.Create(now));

                var update2 = Builders <BsonDocument> .Update.Set("Data", BsonDocument.Parse(model.Data));

                var update = Builders <BsonDocument> .Update.Combine(update1, update2);

                mongo.UpdateOne(Constant.MaterialCollectionName, filter, update);
            }

            return(Json(new
            {
                Code = 200,
                Msg = "保存成功!",
                ID = objectId
            }));
        }
Ejemplo n.º 21
0
        public async Task <bool> UpdateUserAsync(FilterDefinition <BsonDocument> filter, UpdateUserInfo updateUser)
        {
            try
            {
                UpdateDefinition <BsonDocument> update = Builders <BsonDocument> .Update.Set("updateAt", BsonDateTime.Create(DateTime.Now));

                if (updateUser.username != null)
                {
                    FilterDefinition <BsonDocument> nameFilter = Builders <BsonDocument> .Filter.Eq("username", updateUser.username);

                    BsonDocument checkUser = await mCollection.Find(nameFilter).FirstAsync();

                    if (checkUser != null)
                    {
                        return(false);
                    }
                    update = update.Set("username", updateUser.username);
                }
                if (updateUser.password != null)
                {
                    string newPassword = Utilities.CalcuteSHA256Hash(updateUser.password);
                    update = update.Set("password", newPassword);
                }
                if (updateUser.email != null)
                {
                    update = update.Set("email", updateUser.email);
                }
                UpdateResult result = mCollection.UpdateOne(filter, update);
                return(result.ModifiedCount > 0);
            }
            catch
            {
                return(false);
            }
        }