public void SetUp()
        {
            var configurationClient = new ConfigurationClient(ApiTestFixture.ConfigurationServerUri);

            sampleConfig = GenerateSampleConfigData();

            gettingNonExistConfig = () => configurationClient.GetConfiguration<object>("non-exist");

            configurationClient.SetConfiguration("application", sampleConfig);

            getNewCreatedConfig = configurationClient.GetConfiguration<SampleConfigData>("application");
        }
 public static void SaveActiveProfile(Profile profile, string id)
 {
     ConfigurationClient.Set <string>(MakeConfNamespace(id), "active_profile", profile.Id);
 }
        public async Task HelloWorldExtended()
        {
            var connectionString = TestEnvironment.ConnectionString;

            #region Snippet:AzConfigSample2_CreateConfigurationClient
            var client = new ConfigurationClient(connectionString);
            #endregion

            #region Snippet:AzConfigSample2_CreateConfigurationSettingAsync
            var betaEndpoint        = new ConfigurationSetting("endpoint", "https://beta.endpoint.com", "beta");
            var betaInstances       = new ConfigurationSetting("instances", "1", "beta");
            var productionEndpoint  = new ConfigurationSetting("endpoint", "https://production.endpoint.com", "production");
            var productionInstances = new ConfigurationSetting("instances", "1", "production");
            #endregion

            #region Snippet:AzConfigSample2_AddConfigurationSettingAsync
            await client.AddConfigurationSettingAsync(betaEndpoint);

            await client.AddConfigurationSettingAsync(betaInstances);

            await client.AddConfigurationSettingAsync(productionEndpoint);

            await client.AddConfigurationSettingAsync(productionInstances);

            #endregion

            #region Snippet:AzConfigSample2_GetConfigurationSettingAsync
            ConfigurationSetting instancesToUpdate = await client.GetConfigurationSettingAsync(productionInstances.Key, productionInstances.Label);

            #endregion

            #region Snippet:AzConfigSample2_SetUpdatedConfigurationSettingAsync
            instancesToUpdate.Value = "5";
            await client.SetConfigurationSettingAsync(instancesToUpdate);

            #endregion


            #region Snippet:AzConfigSample2_GetConfigurationSettingsAsync
            var selector = new SettingSelector {
                LabelFilter = "production"
            };

            Debug.WriteLine("Settings for Production environment:");
            await foreach (ConfigurationSetting setting in client.GetConfigurationSettingsAsync(selector))
            {
                Console.WriteLine(setting);
            }
            #endregion

            // Delete the Configuration Settings from the Configuration Store.
            #region Snippet:AzConfigSample2_DeleteConfigurationSettingAsync
            await client.DeleteConfigurationSettingAsync(betaEndpoint.Key, betaEndpoint.Label);

            await client.DeleteConfigurationSettingAsync(betaInstances.Key, betaInstances.Label);

            await client.DeleteConfigurationSettingAsync(productionEndpoint.Key, productionEndpoint.Label);

            await client.DeleteConfigurationSettingAsync(productionInstances.Key, productionInstances.Label);

            #endregion
        }
 private void CreateConfigSet(ConfigurationClient client)
 {
     clientStore.Add(client.ClientId, client);
     innerStore.Add(client.ClientId, new Dictionary <Type, ConfigInstance>());
 }
 public AppConfigHelper(string appConfigConnectionString)
 {
     this.client = new ConfigurationClient(appConfigConnectionString);
 }
Exemple #6
0
        public static void Сохранить(string directory, bool ОставитьПредыдущююВерсию, bool async)
        {
            //не сохранять если используется внешний кеш
            //if (MemoryCache.IsMemoryCacheClient)
            //    return;
            var task = System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                lock (lockCacheXml)
                {
                    try
                    {
                        var sb                      = new StringBuilder();
                        var settings                = new XmlWriterSettings();
                        settings.Indent             = true;
                        settings.OmitXmlDeclaration = true;

                        if (!System.IO.Directory.Exists(directory))
                        {
                            System.IO.Directory.CreateDirectory(directory);
                        }

                        var last_directory = Path.Combine(directory, string.Format("{0:yyyy.MM.dd__hh.mm.ss}", DateTime.Now));
                        if (ОставитьПредыдущююВерсию && !System.IO.Directory.Exists(last_directory))
                        {
                            System.IO.Directory.CreateDirectory(last_directory);
                        }

                        var ser = new System.Runtime.Serialization.DataContractSerializer(typeof(Dictionary <string, КешЭлемент>), КешЭлемент.KnownTypeList());
                        foreach (var item in Items.AsParallel().GroupBy(p => Regex.Match(p.Key, @"(.+?):").Groups[1].Value))
                        {
                            try
                            {
                                sb = new StringBuilder();
                                using (var xml = XmlWriter.Create(sb, settings))
                                {
                                    ser.WriteObject(xml, item.ToDictionary(p => p.Key, e => e.Value));
                                    xml.Flush();

                                    var file = System.IO.Path.Combine(directory, item.Key + ".cache");
                                    if (ОставитьПредыдущююВерсию && System.IO.File.Exists(file))
                                    {
                                        System.IO.File.Move(file, System.IO.Path.Combine(last_directory, item.Key + ".cache"));
                                    }
                                    System.IO.File.WriteAllText(file, sb.ToString());
                                    System.Threading.Thread.Sleep(100);
                                }
                            }
                            catch (Exception ex)
                            {
                                ConfigurationClient.WindowsLog(ex.ToString(), "", item.Key, "Cache.Сохранить");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ConfigurationClient.WindowsLog(ex.ToString(), "", "system", "Cache.Сохранить");
                    }
                }
            });

            if (!async)
            {
                task.Wait();
            }
        }
 public AppConfigurationClient(AppConfig config)
 {
     this.client = new ConfigurationClient(config.AppConfigurationConnectionString);
     this.config = config;
 }
Exemple #8
0
 public AzureConfigurationProvider(string connectionString)
     : base()
 {
     _client = new ConfigurationClient(connectionString);
 }
Exemple #9
0
        public decimal СохранитьФайлПолностью(object id_node, string ИдентификаторФайла, string ИмяФайла, string Описание, byte[] stream, Хранилище хранилище, string user, string domain)
        {
            try
            {
                var data = new DataClient();

                //удалить старый файл
                if (!string.IsNullOrEmpty(ИдентификаторФайла))
                {
                    var file = new DataClient()._СписокФайлов(id_node, хранилище, domain).FirstOrDefault(p => p.ИдентификаторФайла == ИдентификаторФайла);
                    if (file != null)
                    {
                        data.УдалитьРаздел(false, false, new decimal[] { file.id_node }, хранилище, user, domain);
                    }
                }

                //Проверить существует ли хранилище
                if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["ОперативноеХранилище"]))
                {
                    throw new Exception("Не задан путь к файловому хранилищу в файле конфигурации 'appSettings//ОперативноеХранилище'");
                }

                var path = Path.Combine(System.Configuration.ConfigurationManager.AppSettings["ОперативноеХранилище"], domain);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                #region save file
                var filename = string.Format("{0}", ИмяФайла.Replace(" ", "_"));
                if (stream != null)
                {
                    var full_filename = Path.Combine(path, filename);
                    if (System.IO.File.Exists(full_filename))
                    {
                        var Extension = Path.GetExtension(filename);
                        var FileNameWithoutExtension = Path.GetFileNameWithoutExtension(filename);
                        for (int i = 1; ; i++)
                        {
                            filename      = string.Format("{0}_{1:f0}{2}", FileNameWithoutExtension, i, Extension);
                            full_filename = Path.Combine(path, filename);

                            if (!System.IO.File.Exists(full_filename))
                            {
                                break;
                            }
                        }
                    }

                    System.IO.File.WriteAllBytes(full_filename, stream);

                    //#region асинхронное сохранение на диск
                    //System.Threading.Tasks.Task.Factory.StartNew((object obj) =>
                    //{
                    //    try
                    //    {
                    //        System.IO.File.WriteAllBytes((string)((object[])obj)[0], (byte[])((object[])obj)[1]);
                    //    }
                    //    catch (Exception)
                    //    {
                    //    }
                    //}, new object[] { full_filename, stream });
                    //#endregion
                }
                #endregion

                //сохранить новый файл
                var values = new Dictionary <string, Value>(6);
                values.Add("НазваниеОбъекта", new Value(ИмяФайла));
                values.Add("ИдентификаторОбъекта", new Value(ИдентификаторФайла));
                values.Add("ОписаниеФайла", new Value(Описание));
                values.Add("ПолноеИмяФайла", new Value(filename));
                values.Add("РазмерФайла", new Value(stream == null ? 0 : stream.Length));
                values.Add("MimeType", new Value(GetMimeType(ИмяФайла)));
                var id_file = data.ДобавитьРаздел(id_node, "Файл", values, false, хранилище, false, user, domain);

                #region Обновить кол-во в кеше
                var __keyfull = MemoryCache.Path(domain, хранилище, Convert.ToDecimal(id_node)) + "@@КоличествоФайлов";
                var _tmp      = MemoryCache.Get(__keyfull);
                if (_tmp != null)
                {
                    _tmp.obj.Значение = Convert.ToInt32(_tmp.obj.Значение) + 1;
                    if (MemoryCache.IsMemoryCacheClient)
                    {
                        MemoryCache.Set(__keyfull, _tmp);
                    }
                }
                #endregion

                return(id_file);
            }
            catch (Exception ex)
            {
                ConfigurationClient.WindowsLog(ex.ToString(), user, domain, "СохранитьФайлПолностью");
                return(0);
            }
        }
Exemple #10
0
        //protected static readonly object trimmingLockObject = new System.Object();
        public byte[] ПолучитьФайлПросмотр(object id_file, ImageType type, int width, int height, ImageFormat format, long Качество, КонструкторИзображения Конструктор, string domain)
        {
            #region FileName
            var data     = new DataClient();
            var path     = Path.Combine(System.Configuration.ConfigurationManager.AppSettings["ПросмотрХранилище"], domain);
            var filename = null as string;

            switch (format)
            {
            case ImageFormat.Jpg:
            {
                filename = string.Format("{0:f0}_{1:0}x{2:0}_{3}_{4}_{5}.jpg",
                                         id_file, width, height,
                                         type.ToString(), Качество,
                                         Path.GetFileNameWithoutExtension(data.ПолучитьЗначение <string>(id_file, "НазваниеОбъекта", Хранилище.Оперативное, domain)));
            }
            break;

            case ImageFormat.Png:
            {
                filename = string.Format("{0:f0}_{1:0}x{2:0}_{3}_{4}.png",
                                         id_file, width, height,
                                         type.ToString(),
                                         Path.GetFileNameWithoutExtension(data.ПолучитьЗначение <string>(id_file, "НазваниеОбъекта", Хранилище.Оперативное, domain)));
            }
            break;
            }
            #endregion

            var full_filename = Path.Combine(path, filename);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            if (System.IO.File.Exists(full_filename))
            {
                return(System.IO.File.ReadAllBytes(full_filename));
            }
            else
            {
                var imgOutput = null as Bitmap;
                var canvas    = null as Graphics;
                try
                {
                    using (var output = new MemoryStream())
                    {
                        try
                        {
                            var image      = null as Bitmap;
                            var filestream = ПолучитьФайлПолностью(id_file, Хранилище.Оперативное, domain);
                            if (filestream != null)
                            {
                                using (var mc = new MemoryStream(filestream))
                                    using (image = new Bitmap(mc))
                                    {
                                        #region очистить фон
                                        if (Конструктор != null && Конструктор.ПрозрачныйФон)
                                        {
                                            var firstPixelColor = image.GetPixel(0, 0);
                                            if (firstPixelColor != null && Color.Transparent.ToArgb() != firstPixelColor.ToArgb())
                                            {
                                                var floodFiller = new UnsafeQueueLinearFloodFiller()
                                                {
                                                    Bitmap    = new PictureBoxScroll.EditableBitmap(image, PixelFormat.Format32bppArgb),
                                                    FillColor = Color.Transparent,
                                                    Tolerance = new byte[] { 5, 5, 5 }
                                                };
                                                floodFiller.FloodFill(new Point(0, 0));

                                                if (floodFiller.Bitmap != null && floodFiller.Bitmap.Bitmap != null)
                                                {
                                                    image.Dispose();
                                                    image = new Bitmap(floodFiller.Bitmap.Bitmap);
                                                }
                                            }
                                        }
                                        #endregion

                                        #region trimming
                                        if (Конструктор != null && Конструктор.ОбрезатьПустоеМесто)
                                        {
                                            // Find the min/max non-white/transparent pixels
                                            var min = new Point(int.MaxValue, int.MaxValue);
                                            var max = new Point(int.MinValue, int.MinValue);


                                            var isAlpha = image.PixelFormat.HasFlag(PixelFormat.Alpha);
                                            for (int x = 0; x < image.Width; ++x)
                                            {
                                                for (int y = 0; y < image.Height; ++y)
                                                {
                                                    var pixelColor = image.GetPixel(x, y);

                                                    if ((pixelColor.R < 245 && pixelColor.G < 245 && pixelColor.B < 245 && pixelColor.A > 0) ||
                                                        (isAlpha && pixelColor.A > 0))
                                                    {
                                                        if (x < min.X)
                                                        {
                                                            min.X = x;
                                                        }
                                                        if (y < min.Y)
                                                        {
                                                            min.Y = y;
                                                        }

                                                        if (x > max.X)
                                                        {
                                                            max.X = x;
                                                        }
                                                        if (y > max.Y)
                                                        {
                                                            max.Y = y;
                                                        }
                                                    }
                                                }
                                            }

                                            var cropRectangle = new Rectangle(min.X, min.Y, max.X - min.X, max.Y - min.Y);
                                            var newBitmap     = new Bitmap(cropRectangle.Width, cropRectangle.Height);
                                            newBitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution);

                                            var g = Graphics.FromImage(newBitmap);
                                            g.DrawImage(image, 0, 0, cropRectangle, GraphicsUnit.Pixel);
                                            g.Flush();

                                            image.Dispose();
                                            image = newBitmap;
                                        }
                                        #endregion

                                        var newSize = new Size(width, height);
                                        switch (type)
                                        {
                                        case ImageType.Full:
                                        {
                                            newSize                   = new Size(width, height);
                                            imgOutput                 = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppArgb);
                                            canvas                    = Graphics.FromImage(imgOutput);
                                            canvas.SmoothingMode      = SmoothingMode.Default;
                                            canvas.CompositingQuality = CompositingQuality.HighQuality;
                                            canvas.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                                            if (format == ImageFormat.Jpg)
                                            {
                                                canvas.Clear(Color.White);
                                            }
                                            canvas.DrawImage(image, 0, 0, newSize.Width, newSize.Height);
                                            canvas.Flush();
                                        }
                                        break;

                                        case ImageType.Thumbnail:
                                        {
                                            int _width = Math.Min(image.Size.Height, image.Size.Width);
                                            imgOutput                 = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppArgb);
                                            canvas                    = Graphics.FromImage(imgOutput);
                                            canvas.SmoothingMode      = SmoothingMode.Default;
                                            canvas.CompositingQuality = CompositingQuality.HighQuality;
                                            canvas.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                                            if (format == ImageFormat.Jpg)
                                            {
                                                canvas.Clear(Color.White);
                                            }
                                            canvas.DrawImage(image, new Rectangle(0, 0, newSize.Width, newSize.Height), new Rectangle(0, 0, _width, _width), GraphicsUnit.Pixel);
                                            canvas.Flush();
                                        }
                                        break;

                                        case ImageType.Resize:
                                        {
                                            if (newSize.Width > 0 && newSize.Height == 0)                // Сжатие по ширине (принудительное)
                                            {
                                                newSize.Height = (int)(((double)newSize.Width / (double)image.Size.Width) * image.Size.Height);
                                            }
                                            else if (newSize.Width == 0 && newSize.Height > 0)          // Сжатие по высоте (принудительное)
                                            {
                                                newSize.Width = (int)(((double)newSize.Height / (double)image.Size.Height) * image.Size.Width);
                                            }
                                            else
                                            {
                                                int sourceWidth  = image.Size.Width;
                                                int sourceHeight = image.Size.Height;

                                                float nPercent  = 0;
                                                float nPercentW = 0;
                                                float nPercentH = 0;

                                                nPercentW = ((float)newSize.Width / (float)sourceWidth);
                                                nPercentH = ((float)newSize.Height / (float)sourceHeight);

                                                if (nPercentH < nPercentW)
                                                {
                                                    nPercent = nPercentH;
                                                }
                                                else
                                                {
                                                    nPercent = nPercentW;
                                                }

                                                newSize = new Size((int)(sourceWidth * nPercent), (int)(sourceHeight * nPercent));
                                            }

                                            imgOutput                 = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppArgb);
                                            canvas                    = Graphics.FromImage(imgOutput);
                                            canvas.SmoothingMode      = SmoothingMode.Default;
                                            canvas.CompositingQuality = CompositingQuality.HighQuality;
                                            canvas.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                                            if (format == ImageFormat.Jpg)
                                            {
                                                canvas.Clear(Color.White);
                                            }
                                            canvas.DrawImage(image, 0, 0, newSize.Width, newSize.Height);
                                            canvas.Flush();
                                        }
                                        break;
                                        }

                                        #region Добавить слои из конструктора
                                        if (Конструктор != null && Конструктор.Слои != null && canvas != null)
                                        {
                                            foreach (var item in Конструктор.Слои)
                                            {
                                                if (item.id_file == null || item.id_file.Equals(0m))
                                                {
                                                    continue;
                                                }

                                                using (var mcLayer = new MemoryStream(ПолучитьФайлПолностью(item.id_file, Хранилище.Оперативное, domain)))
                                                    using (var imageLayer = new Bitmap(mcLayer))
                                                    {
                                                        canvas.DrawImage(imageLayer, item.x, item.y,
                                                                         Convert.ToInt32(imageLayer.Width * (item.width > 0 ? item.width : 1.0)),
                                                                         Convert.ToInt32(imageLayer.Height * (item.height > 0 ? item.height : 1.0)));
                                                    }
                                            }
                                        }
                                        #endregion
                                    }
                            }
                            else
                            {
                                imgOutput = new Bitmap(width, height);
                                canvas    = Graphics.FromImage(imgOutput);
                                canvas.Clear(Color.White);
                                canvas.DrawRectangle(Pens.Gray, 0, 0, width - 1, height - 1);
                                canvas.DrawString(
                                    "Not Found " + data.ПолучитьЗначение <string>(id_file, "НазваниеОбъекта", Хранилище.Оперативное, domain),
                                    new Font("Tahoma", 8),
                                    Brushes.Gray,
                                    new RectangleF(0, 0, width, height),
                                    new StringFormat()
                                {
                                    Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center
                                });
                            }
                        }
                        catch (Exception ex)
                        {
                            imgOutput = new Bitmap(width, height);
                            canvas    = Graphics.FromImage(imgOutput);
                            canvas.Clear(Color.White);
                            canvas.DrawRectangle(Pens.Gray, 0, 0, width - 1, height - 1);
                            canvas.DrawString(
                                data.ПолучитьЗначение <string>(id_file, "НазваниеОбъекта", Хранилище.Оперативное, domain),
                                new Font("Tahoma", 8),
                                Brushes.Gray,
                                new RectangleF(0, 0, width, height),
                                new StringFormat()
                            {
                                Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center
                            });

                            ConfigurationClient.WindowsLog("FileService", string.Empty, domain, ex.ToString());
                        }

                        #region Вывод
                        switch (format)
                        {
                        case ImageFormat.Jpg:
                        {
                            var ep = new EncoderParameters(1);
                            ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Качество);
                            ImageCodecInfo imageCodecInfo = null;
                            foreach (ImageCodecInfo item in ImageCodecInfo.GetImageEncoders())
                            {
                                if (item.MimeType == "image/jpeg")
                                {
                                    imageCodecInfo = item;
                                    break;
                                }
                            }
                            imgOutput.Save(output, imageCodecInfo, ep);
                        }
                        break;

                        case ImageFormat.Png:
                        {
                            imgOutput.Save(output, System.Drawing.Imaging.ImageFormat.Png);
                        }
                        break;
                        }

                        //сохранить файл
                        System.IO.File.WriteAllBytes(full_filename, output.ToArray());
                        #endregion

                        return(output.ToArray());
                    }
                }
                finally
                {
                    if (canvas != null)
                    {
                        canvas.Dispose();
                    }
                    if (imgOutput != null)
                    {
                        imgOutput.Dispose();
                    }
                }
            }
        }
Exemple #11
0
        public UploadResponce СохранитьФайл(UploadRequest request)
        {
            var data = new DataClient();

            try
            {
                var path = Path.Combine(System.Configuration.ConfigurationManager.AppSettings["ОперативноеХранилище"], request.domain);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                var tmp_file = Path.Combine(path, Path.GetRandomFileName());
                using (var file = System.IO.File.Create(tmp_file))
                {
                    var chunkSize = 1024 * 64;
                    var buffer    = new byte[chunkSize];
                    var bytesRead = 0;
                    while ((bytesRead = request.FileByteStream.Read(buffer, 0, chunkSize)) > 0)
                    {
                        file.Write(buffer, 0, bytesRead);
                    }
                }

                //удалить старый файл
                if (!string.IsNullOrEmpty(request.ИдентификаторФайла))
                {
                    var file = new DataClient()._СписокФайлов(request.id_node, request.хранилище, request.domain).FirstOrDefault(p => p.ИдентификаторФайла == request.ИдентификаторФайла);
                    if (file != null)
                    {
                        data.УдалитьРаздел(false, false, new decimal[] { file.id_node }, request.хранилище, request.user, request.domain);
                    }
                }

                //Проверить существует ли хранилище
                if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["ОперативноеХранилище"]))
                {
                    throw new Exception("Не задан путь к файловому хранилищу в файле конфигурации 'appSettings//ОперативноеХранилище'");
                }


                var filename = string.Format("{0}", request.ИмяФайла.Replace(" ", "_"));

                //если добавляемый файл существует, заменить имя
                var full_filename = Path.Combine(path, filename);
                if (System.IO.File.Exists(full_filename))
                {
                    var Extension = Path.GetExtension(filename);
                    var FileNameWithoutExtension = Path.GetFileNameWithoutExtension(filename);
                    for (int i = 1; ; i++)
                    {
                        filename      = string.Format("{0}_{1:f0}{2}", FileNameWithoutExtension, i, Extension);
                        full_filename = Path.Combine(path, filename);

                        if (!System.IO.File.Exists(full_filename))
                        {
                            break;
                        }
                    }
                }
                if (System.IO.File.Exists(tmp_file))
                {
                    System.IO.File.Move(tmp_file, full_filename);
                }

                //сохранить новый файл
                var values = new Dictionary <string, Value>();
                values.Add("НазваниеОбъекта", new Value(request.ИмяФайла));
                values.Add("ИдентификаторОбъекта", new Value(request.ИдентификаторФайла));
                values.Add("ОписаниеФайла", new Value(request.Описание));
                values.Add("РазмерФайла", new Value(request.Length));
                values.Add("MimeType", new Value(GetMimeType(request.ИмяФайла)));
                values.Add("ПолноеИмяФайла", new Value(filename));
                var id_file = data.ДобавитьРаздел(request.id_node, "Файл", values, false, request.хранилище, true, request.user, request.domain);

                #region Обновить кол-во в кеше
                var __keyfull = MemoryCache.Path(request.domain, request.хранилище, request.id_node) + "@@КоличествоФайлов";
                var _tmp      = MemoryCache.Get(__keyfull);
                if (_tmp != null)
                {
                    _tmp.obj.Значение = Convert.ToInt32(_tmp.obj.Значение) + 1;
                    if (MemoryCache.IsMemoryCacheClient)
                    {
                        MemoryCache.Set(__keyfull, _tmp);
                    }
                }
                #endregion

                return(new UploadResponce()
                {
                    id_file = id_file
                });
            }
            catch (Exception ex)
            {
                ConfigurationClient.WindowsLog(ex.ToString(), request.user, request.domain, "СохранитьФайл", request.ИмяФайла);
                return(new UploadResponce());
            }
            finally
            {
                request.Dispose();
            }
        }
Exemple #12
0
        protected override string DownloadSecrets()
        {
            var client = new ConfigurationClient(EndpointUri, new azIdentity.DefaultAzureCredential());

            return(client.GetConfigurationSetting(SecretId, SecretId).Value.Value);
        }
        public void Load()
        {
            lock (this) {
                if (source == null)
                {
                    return;
                }

                loaded = false;

                foreach (Column column in this)
                {
                    if (column.Id != null)
                    {
                        string @namespace = MakeNamespace(column.Id);
                        column.Visible = ConfigurationClient.Get <bool> (@namespace, "visible", column.Visible);
                        column.Width   = ConfigurationClient.Get <double> (@namespace, "width", column.Width);
                    }
                }

                // Create a copy so we can read the original index
                List <Column> columns = new List <Column> (Columns);

                Columns.Sort(delegate(Column a, Column b) {
                    int a_order = a.Id == null ? -1 : ConfigurationClient.Get <int> (
                        MakeNamespace(a.Id), "order", columns.IndexOf(a));
                    int b_order = b.Id == null ? -1 : ConfigurationClient.Get <int> (
                        MakeNamespace(b.Id), "order", columns.IndexOf(b));

                    return(a_order.CompareTo(b_order));
                });

                string sort_ns        = String.Format("{0}.{1}.{2}", root_namespace, unique_source_id, "sort");
                string sort_column_id = ConfigurationClient.Get <string> (sort_ns, "column", null);
                if (sort_column_id != null)
                {
                    ISortableColumn sort_column = null;
                    foreach (Column column in this)
                    {
                        if (column.Id == sort_column_id)
                        {
                            sort_column = column as ISortableColumn;
                            break;
                        }
                    }

                    if (sort_column != null)
                    {
                        int      sort_dir  = ConfigurationClient.Get <int> (sort_ns, "direction", 0);
                        SortType sort_type = sort_dir == 0 ? SortType.None : sort_dir == 1 ? SortType.Ascending : SortType.Descending;
                        sort_column.SortType = sort_type;
                        base.SortColumn      = sort_column;
                    }
                }
                else
                {
                    base.SortColumn = null;
                }

                loaded = true;
            }

            OnUpdated();
        }
        /// <summary>
        /// Initializes the configuration builder lazily.
        /// </summary>
        /// <param name="name">The friendly name of the provider.</param>
        /// <param name="config">A collection of the name/value pairs representing builder-specific attributes specified in the configuration for this provider.</param>
        protected override void LazyInitialize(string name, NameValueCollection config)
        {
            // Default 'Optional' to false. base.LazyInitialize() will override if specified in config.
            Optional = false;

            base.LazyInitialize(name, config);

            // keyFilter
            _keyFilter = UpdateConfigSettingWithAppSettings(keyFilterTag);
            if (String.IsNullOrWhiteSpace(_keyFilter))
            {
                _keyFilter = null;
            }

            // labelFilter
            // Place some restrictions on label filter, similar to the .net core provider.
            // The idea is to restrict queries to one label, and one label only. Even if that
            // one label is the "empty" label. Doing so will remove the decision making process
            // from this builders hands about which key/value/label tuple to choose when there
            // are multiple.
            _labelFilter = UpdateConfigSettingWithAppSettings(labelFilterTag);
            if (String.IsNullOrWhiteSpace(_labelFilter))
            {
                _labelFilter = null;
            }
            else if (_labelFilter.Contains('*') || _labelFilter.Contains(','))
            {
                throw new ArgumentException("The characters '*' and ',' are not supported in label filters.", labelFilterTag);
            }

            // acceptDateTime
            _dateTimeFilter = DateTimeOffset.TryParse(UpdateConfigSettingWithAppSettings(dateTimeFilterTag), out _dateTimeFilter) ? _dateTimeFilter : DateTimeOffset.MinValue;

            // Azure Key Vault Integration
            _useKeyVault = (UpdateConfigSettingWithAppSettings(useKeyVaultTag) != null) ? Boolean.Parse(config[useKeyVaultTag]) : _useKeyVault;
            if (_useKeyVault)
            {
                _kvClientCache = new ConcurrentDictionary <Uri, SecretClient>(EqualityComparer <Uri> .Default);
            }


            // Always allow 'connectionString' to override black magic. But we expect this to be null most of the time.
            _connectionString = UpdateConfigSettingWithAppSettings(connectionStringTag);
            if (String.IsNullOrWhiteSpace(_connectionString))
            {
                _connectionString = null;

                // Use Endpoint instead
                string uri = UpdateConfigSettingWithAppSettings(endpointTag);
                if (!String.IsNullOrWhiteSpace(uri))
                {
                    try
                    {
                        _endpoint = new Uri(uri);
                        _client   = new ConfigurationClient(_endpoint, new DefaultAzureCredential());
                    }
                    catch (Exception ex)
                    {
                        if (!Optional)
                        {
                            throw new ArgumentException($"Exception encountered while creating connection to Azure App Configuration store.", ex);
                        }
                    }
                }
                else
                {
                    throw new ArgumentException($"An endpoint URI or connection string must be provided for connecting to Azure App Configuration service via the '{endpointTag}' or '{connectionStringTag}' attribute.");
                }
            }
            else
            {
                // If we get here, then we should try to connect with a connection string.
                try
                {
                    _client = new ConfigurationClient(_connectionString);
                }
                catch (Exception ex)
                {
                    if (!Optional)
                    {
                        throw new ArgumentException($"Exception encountered while creating connection to Azure App Configuration store.", ex);
                    }
                }
            }

            // At this point we've got all our ducks in a row and are ready to go. And we know that
            // we will be used, because this is the 'lazy' initializer. But let's handle one oddball case
            // before we go.
            // If we have a keyFilter set, then we will always query a set of values instead of a single
            // value, regardless of whether we are in strict/expand/greedy mode. But if we're not in
            // greedy mode, then the base KeyValueConfigBuilder will still request each key/value it is
            // interested in one at a time, and only cache that one result. So we will end up querying the
            // same set of values from the AppConfig service for every value. Let's only do this once and
            // cache the entire set to make those calls to GetValueInternal read from the cache instead of
            // hitting the service every time.
            if (_keyFilter != null && Mode != KeyValueMode.Greedy)
            {
                EnsureGreedyInitialized();
            }
        }
 public AppConfigurationClient(AppConfig config, IConfigurationClientFactory clientFactory)
 {
     this.client = clientFactory.Create();
     this.config = config;
 }
Exemple #16
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", "delete", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            string  connectionstring = req.Query["connectionstring"];
            string  name             = req.Query["name"];
            string  value            = req.Query["value"];
            string  requestBody      = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data             = JsonConvert.DeserializeObject(requestBody);

            if (req.Method.Equals("POST"))
            {
                connectionstring = connectionstring ?? data?.connectionstring;
                name             = name ?? data?.name;
                value            = value ?? data?.value;
                Azure.Response <ConfigurationSetting> res;
                try
                {
                    var client  = new ConfigurationClient(connectionstring);
                    var setting = new ConfigurationSetting(name, value);
                    res = client.Set(setting);
                }
                catch (NullReferenceException ex)
                {
                    log.LogError("Object reference not set to an instance of an object. Can be due to incorrect connection string.\n" + ex);
                    return(new BadRequestObjectResult("Object reference not set to an instance of an object. Can be due to incorrect connection string.\n" + ex));
                }
                catch (Exception ex)
                {
                    log.LogError(ex.ToString());
                    return(new BadRequestObjectResult(ex));
                }

                return(new OkObjectResult($"{req.Method} AppConfig {name} \n {res}"));
            }

            if (req.Method.Equals("DELETE"))
            {
                connectionstring = connectionstring ?? data?.connectionstring;
                name             = name ?? data?.name;
                Azure.Response res;
                try
                {
                    var client = new ConfigurationClient(connectionstring);
                    res = client.Delete(name);
                }
                catch (NullReferenceException ex)
                {
                    log.LogError("Object reference not set to an instance of an object. Can be due to incorrect connection string.\n" + ex);
                    return(new BadRequestObjectResult("Object reference not set to an instance of an object. Can be due to incorrect connection string.\n" + ex));
                }
                catch (Exception ex)
                {
                    log.LogError(ex.ToString());
                    return(new BadRequestObjectResult(ex));
                }

                return(new OkObjectResult($"{req.Method} AppConfig {name} \n {res}"));
            }

            log.LogError("Bad Request");
            return(new BadRequestResult());
        }
Exemple #17
0
 public GlobalConfigurationProvider(ConfigurationClient configurationClient)
 {
     this.configurationClient = configurationClient;
 }
Exemple #18
0
 public async Task CleanUp()
 {
     var connectionString       = Environment.GetEnvironmentVariable("APPCONFIGURATION_CONNECTION_STRING");
     ConfigurationClient client = new ConfigurationClient(connectionString);
     await client.DeleteConfigurationSettingAsync("some_key");
 }
Exemple #19
0
        private static IEnumerable <decimal> СписокРазделов(string domain)
        {
            using (DataClasses.ClientDataContext db = new DataClasses.ClientDataContext(domain))
            {
                return(db.ExecuteQuery <decimal>(@"select [id_node] from assembly_tblNode WITH(NOLOCK) where [type] = 'ТипДанных' and HashCode like {0}", ConfigurationClient.GetHashCode(Convert.ToDecimal(ConfigurationClient.СистемныеПапки.азделТипы), 0, Хранилище.Конфигурация, domain)).ToArray());

                //var command = ((SqlConnection)db.Connection).CreateCommand();
                //command.CommandText = "select [id_node] from assembly_tblNode WITH(NOLOCK) where [type] = 'ТипДанных' and HashCode like {0}";
                //return Convert.ToDecimal(command.ExecuteScalar());
            }
        }
Exemple #20
0
        public static IEnumerable <КешХешьТаблица> СписокЗависимыхТаблиц(string тип, Хранилище хранилище, string domain)
        {
            try
            {
                var key = domain + ":Z:КешХешьТаблица:";
                //if (MemoryCache.IsMemoryCacheClient)
                //{
                //    var items = null as List<string>;
                //    using (var redis = ClientRedis.Clients.GetReadOnlyClient())
                //    {
                //        items = redis.SearchKeys(key + "*");
                //    }
                //    if (items.Count > 0)
                //    {
                //        var caching = ClientRedis.Clients.GetAll<КешХешьТаблица>(items)
                //            .Where(p => p.Value.Хранилище == хранилище && p.Value.ВремяЖизни == null)
                //            .Select(p => p.Value);

                //        if (caching.Count() == 0)
                //            return new КешХешьТаблица[0];

                //        var tables = caching.Where(p =>
                //                p.IsComplite
                //                && p.ЗависимыеТипы != null
                //                && p.ЗависимыеТипы.Length > 0
                //                && p.ЗависимыеТипы.FirstOrDefault(e => e == тип) != null);
                //        if (tables.Count() == 0)
                //            return new КешХешьТаблица[0];

                //        return tables.ToArray();
                //    }
                //}
                //else
                //{
                var caching = Caching.Cache.Items
                              .AsParallel()
                              .Where(p => p.Value is КешХешьТаблица &&
                                     p.Key != null &&
                                     p.Key.StartsWith(key) &&
                                     ((КешХешьТаблица)p.Value).Хранилище == хранилище &&
                                     ((КешХешьТаблица)p.Value).ВремяЖизни == null)
                              .Select(p => p.Value).Cast <КешХешьТаблица>();
                if (caching.Count() == 0)
                {
                    return(new КешХешьТаблица[0]);
                }

                var tables = caching.Where(p =>
                                           p.IsComplite &&
                                           p.ЗависимыеТипы != null &&
                                           p.ЗависимыеТипы.Length > 0 &&
                                           p.ЗависимыеТипы.FirstOrDefault(e => e == тип) != null);
                if (tables.Count() == 0)
                {
                    return(new КешХешьТаблица[0]);
                }

                return(tables.ToArray());
                //}
            }
            catch (Exception ex)
            {
                ConfigurationClient.WindowsLog("RosService.Caching.СписокЗависимыхТаблиц", string.Empty, domain, тип, ex.ToString());
            }
            return(new КешХешьТаблица[0]);
        }
Exemple #21
0
        private static IEnumerable <CompileType> СписокАтрибутов(decimal id_node, string domain)
        {
            //using (new TransactionScope(TransactionScopeOption.Suppress))
            using (DataClasses.ClientDataContext db = new DataClasses.ClientDataContext(domain))
                using (var table = new DataSet()
                {
                    RemotingFormat = SerializationFormat.Binary, EnforceConstraints = false
                })
                {
                    #region sql
                    var sql = string.Format(@"
                    ;with
                        БазовыйТип        as (select id_node, [double_value] 'value' from assembly_tblValueHref WITH(NOLOCK) where [type] = 'БазовыйТип'),
                        СсылкаНаТипДанных as (select id_node, [double_value] 'value' from assembly_tblValueHref WITH(NOLOCK) where [type] = 'СсылкаНаТипДанных'),
                        НомерТипаДаннах   as (select id_node, [double_value] 'value' from assembly_tblValueDouble WITH(NOLOCK) where [type] = 'НомерТипаДаннах'),
                        IsSystem          as (select id_node, [double_value] 'value' from assembly_tblValueBool WITH(NOLOCK) where [type] = 'IsSystem'),
                        IsAutoIncrement   as (select id_node, [double_value] 'value' from assembly_tblValueBool WITH(NOLOCK) where [type] = 'IsAutoIncrement'),
                        IsReadOnly	      as (select id_node, [double_value] 'value' from assembly_tblValueBool WITH(NOLOCK) where [type] = 'IsReadOnly'),
                        IsSetDefaultValue as (select id_node, [double_value] 'value' from assembly_tblValueBool WITH(NOLOCK) where [type] = 'IsSetDefaultValue'),
                        ИмяТипаДанных     as (select id_node, [string_value] 'value' from assembly_tblValueString WITH(NOLOCK) where [type] = 'ИмяТипаДанных'),
                        Namespace         as (select id_node, [string_value] 'value' from assembly_tblValueString WITH(NOLOCK) where [type] = 'КатегорияТипаДанных'),
                        Описание		  as (select id_node, [string_value] 'value' from assembly_tblValueString WITH(NOLOCK) where [type] = 'НазваниеОбъекта'),

                        СписокТиповДанных as (select  N.id_node, БазовыйТип.value 'БазовыйТип' from assembly_tblNode N WITH(NOLOCK) left join БазовыйТип WITH(NOLOCK) on N.id_node = БазовыйТип.id_node where N.[type] = 'ТипДанных' and N.HashCode like @РазделТипыДанных),
                        СписокАтрибутов as (select N.id_node, N.id_parent, СсылкаНаТипДанных.value 'СсылкаНаТипДанных' from assembly_tblNode N WITH(NOLOCK) left join СсылкаНаТипДанных WITH(NOLOCK) on N.id_node = СсылкаНаТипДанных.id_node where N.[type] = 'Атрибут' and N.HashCode like @РазделТипыДанных),
                        ВыбранныйТипДанных as (select * from СписокТиповДанных WITH(NOLOCK) where id_node = @id_node union all select N.* from СписокТиповДанных N WITH(NOLOCK) inner join ВыбранныйТипДанных on N.id_node = ВыбранныйТипДанных.БазовыйТип and N.id_node > 0)

                    select 
                        СписокАтрибутов.СсылкаНаТипДанных 'id_node',
                        isnull(Namespace.value,'') 'Namespace',
                        isnull(Н1.value,0) 'id_type',
                        isnull(И1.value,'') 'Name',
                        isnull(О1.value,'') 'Описание',
                        isnull(И2.value,'') 'BaseType',
                        isnull(Н2.value,0)  'BaseType.id_type',
                        isnull(И3.value,'') 'ReflectedType',
                        isnull(Н0.value,0) 'DeclaringType',
                        isnull(IsSystem.value,0) 'IsSystem',
                        isnull(IsAutoIncrement.value,0) 'IsAutoIncrement',
                        isnull(IsReadOnly.value,0) 'IsReadOnly',
                        isnull(IsSetDefaultValue.value,0) 'IsSetDefaultValue'

                    from
                        ВыбранныйТипДанных WITH(NOLOCK) 
                        inner join СписокАтрибутов WITH(NOLOCK) on СписокАтрибутов.id_parent = ВыбранныйТипДанных.id_node
                        left join СписокТиповДанных WITH(NOLOCK) on СписокТиповДанных.id_node = СписокАтрибутов.СсылкаНаТипДанных
                        left join Namespace WITH(NOLOCK) on Namespace.id_node = СписокАтрибутов.СсылкаНаТипДанных
                        left join Описание О1 WITH(NOLOCK) on О1.id_node = СписокАтрибутов.СсылкаНаТипДанных
                        left join ИмяТипаДанных И1 WITH(NOLOCK) on И1.id_node = СписокАтрибутов.СсылкаНаТипДанных
                        left join ИмяТипаДанных И2 WITH(NOLOCK) on И2.id_node = СписокТиповДанных.БазовыйТип
                        left join ИмяТипаДанных И3 WITH(NOLOCK) on И3.id_node = ВыбранныйТипДанных.id_node
                        left join НомерТипаДаннах Н0 WITH(NOLOCK) on Н0.id_node = @id_node
                        left join НомерТипаДаннах Н1 WITH(NOLOCK) on Н1.id_node = СписокАтрибутов.СсылкаНаТипДанных
                        left join НомерТипаДаннах Н2 WITH(NOLOCK) on Н2.id_node = СписокТиповДанных.БазовыйТип
                        left join IsSystem WITH(NOLOCK) on IsSystem.id_node = СписокАтрибутов.СсылкаНаТипДанных
                        left join IsAutoIncrement WITH(NOLOCK) on IsAutoIncrement.id_node = СписокАтрибутов.СсылкаНаТипДанных
                        left join IsReadOnly WITH(NOLOCK) on IsReadOnly.id_node = СписокАтрибутов.СсылкаНаТипДанных
                        left join IsSetDefaultValue WITH(NOLOCK) on IsSetDefaultValue.id_node = СписокАтрибутов.СсылкаНаТипДанных", id_node);

                    var command = (db.Connection as SqlConnection).CreateCommand();
                    command.CommandText    = sql;
                    command.CommandTimeout = 120;
                    command.Parameters.AddWithValue("@РазделТипыДанных", ConfigurationClient.GetHashCode(Convert.ToDecimal(ConfigurationClient.СистемныеПапки.азделТипы), 0, Хранилище.Конфигурация, domain));
                    command.Parameters.AddWithValue("@id_node", id_node);
                    new SqlDataAdapter(command).Fill(table);
                    #endregion
                    if (table.Tables[0].AsEnumerable().Count() > 0)
                    {
                        var TypeHashCode = GetTypeHashCode(id_node, domain);
                        foreach (var item in table.Tables[0].AsEnumerable())
                        {
                            var type = GetAssemblyAttribute(item);
                            type.TypeHashCode = TypeHashCode + ConfigurationClient.GetHashKey(item.Field <decimal>("BaseType.id_type"));
                            switch ((MemberTypes)type.MemberType)
                            {
                            case MemberTypes.Undefined:
                            case MemberTypes.Object:
                            {
                                var attrs = СписокАтрибутов(item.Field <decimal>("id_node"), domain);
                                foreach (var subitem in attrs)
                                {
                                    //не добавлять атрибуты из уровня object класса
                                    if (string.IsNullOrEmpty(subitem.ReflectedType) || subitem.ReflectedType == "object")
                                    {
                                        continue;
                                    }

                                    subitem.Name          = type.Name + "." + subitem.Name;
                                    subitem.HashCode      = type.HashCode + subitem.HashCode;
                                    subitem.ReflectedType = type.ReflectedType;
                                    subitem.DeclaringType = type.DeclaringType;
                                    yield return(subitem);

                                    var subitem2 = (CompileType)((ICloneable)subitem).Clone();
                                    subitem2.DeclaringType = 0;
                                    subitem2.ReflectedType = "";
                                    yield return(subitem2);
                                }
                            }
                            break;

                            default:
                                yield return(type);

                                break;
                            }
                        }
                    }
                }
        }
Exemple #22
0
        public static Dictionary <string, ValueContanier> Get(params string[] key)
        {
            var result = new Dictionary <string, ValueContanier>();

            if (key != null && key.Length > 0)
            {
                if (IsMemoryCacheClient)
                {
                    try
                    {
                        foreach (var item in ClientRedis.Get(key))
                        {
                            if (item.Value != null)
                            {
                                result.Add(item.Key, new ValueContanier()
                                {
                                    obj = new Value()
                                    {
                                        Значение = Convert.IsDBNull(item.Value) ? null : item.Value
                                    }
                                });
                            }
                        }

                        //var _tmp = ClientRedis.Get(key);
                        //if (_tmp != null)
                        //{
                        //    return new ValueContanier()
                        //    {
                        //        obj = new Value()
                        //        {
                        //            Значение = _tmp
                        //        }
                        //    };
                        //}
                    }
                    catch (Exception ex)
                    {
                        ConfigurationClient.WindowsLog("MemoryCache:Get", "", "system", key, ex.ToString());
                    }
                }
                else
                {
                    foreach (var item in key)
                    {
                        if (string.IsNullOrEmpty(item))
                        {
                            continue;
                        }

                        var _tmp = null as ValueContanier;
                        if (CurrentValues.TryGetValue(item, out _tmp))
                        {
                            _tmp.cache = DateTime.Now.Add(Timeout);
                            if (!result.ContainsKey(item))
                            {
                                result.Add(item, _tmp);
                            }
                        }
                    }
                }
            }
            return(result);
        }
Exemple #23
0
        public static void КомпилироватьТипДанных(decimal id_node, string domain)
        {
            try
            {
                using (DataClasses.ClientDataContext db = new DataClasses.ClientDataContext(domain))
                {
                    try
                    {
                        if (db.Connection.State != ConnectionState.Open)
                        {
                            db.Connection.Open();
                        }

                        var items = СписокТиповДанных(id_node, domain).ToArray();
                        var type  = items.First();

                        var command = ((SqlConnection)db.Connection).CreateCommand();
                        command.CommandTimeout = 120;
                        command.CommandText    = @"delete from assembly_tblAttribute where id_parent = @id_parent or (id_parent = 0 and Name = @Name)";
                        command.Parameters.AddWithValue("@id_parent", type.id_type);
                        command.Parameters.AddWithValue("@Name", type.Name);
                        command.ExecuteNonQuery();
                        foreach (var item in items)
                        {
                            try
                            {
                                #region sql insert
                                command             = ((SqlConnection)db.Connection).CreateCommand();
                                command.CommandText = string.Format(
                                    @"insert into assembly_tblAttribute (
                                    [id_parent],
                                    [id_type],
                                    [ReflectedType],
                                    [BaseType],
                                    [HashCode],
                                    [TypeHashCode],
                                    [Описание],
                                    [Name],
                                    [Namespace],
                                    [MemberType],
                                    [RegisterType],
                                    [IsAutoIncrement],
                                    [IsReadOnly],
                                    [IsSetDefaultValue]) 
                                values (
                                    {0:f0},{1:f0},'{2}','{3}','{4}','{5}','{6}','{7}','{8}',{9},'{10}',@IsAutoIncrement,@IsReadOnly,@IsSetDefaultValue)",
                                    item.DeclaringType,
                                    item.id_type,
                                    item.ReflectedType,
                                    item.BaseType,
                                    item.HashCode,
                                    item.TypeHashCode,
                                    item.Описание,
                                    item.Name,
                                    item.Namespace,
                                    (int)item.MemberType,
                                    item.RegisterType.ToString());
                                command.Parameters.AddWithValue("@IsAutoIncrement", item.IsAutoIncrement);
                                command.Parameters.AddWithValue("@IsReadOnly", item.IsReadOnly);
                                //command.Parameters.AddWithValue("@IsSystem", item.IsSystem);
                                command.Parameters.AddWithValue("@IsSetDefaultValue", item.IsSetDefaultValue);
                                command.ExecuteNonQuery();
                                #endregion
                            }
                            catch (SqlException ex)
                            {
                                //игнорировать дубликаты
                                if (ex.Number == 2601)
                                {
                                    continue;
                                }
                                throw ex;
                            }
                        }
                    }
                    finally
                    {
                        db.Connection.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                ConfigurationClient.WindowsLog(ex.ToString(), "", domain, "КомпилироватьТипДанных",
                                               id_node,
                                               new Data.DataClient().ПолучитьЗначение <string>(id_node, "НазваниеОбъекта", Хранилище.Конфигурация, domain));
                throw ex;
            }
        }
        public async Task Helpers()
        {
            ConfigurationClient client = TestEnvironment.GetClient();
            var source = new CancellationTokenSource();

            const int numberOfSettings = 2;

            // key prexfix used to partition tests running at the same time so that they don't interract with each other
            var testPartition = Guid.NewGuid().ToString();

            var addedSettings = new List <ConfigurationSetting>(numberOfSettings);

            try {
                // add settings to the store
                for (int i = 0; i < numberOfSettings; i++)
                {
                    var reponse = await client.AddAsync(new ConfigurationSetting($"{testPartition}_{i}", i.ToString()));

                    Assert.AreEqual(200, reponse.Status);
                    addedSettings.Add(reponse.Value);
                }

                var changed = new List <SettingChangedEventArgs>(); // acumulator for detected changes
                var watcher = new ConfigurationWatcher(client, addedSettings.Select((setting) => setting.Key).ToArray());
                watcher.SettingChanged += (sender, e) =>
                {
                    changed.Add(e);
                };
                watcher.Error += (sender, e) =>
                {
                    Assert.Fail(e.Message);
                };

                // start watching for changes
                watcher.Start();

                // do updates in the service store
                for (int i = 0; i < numberOfSettings; i++)
                {
                    var updated = addedSettings[i];
                    updated.Value = (i + 100).ToString();
                    var response = await client.UpdateAsync(updated);
                }

                // wait for updates to be detected
                await Task.Delay(2000);

                await watcher.Stop();

                // assert expectations
                Assert.AreEqual(numberOfSettings, changed.Count);
            }
            finally {
                // delete settings from the service store
                foreach (var setting in addedSettings)
                {
                    var response = await client.DeleteAsync(setting.Key);

                    if (response.Status != 200)
                    {
                        throw new Exception("could not delete setting " + setting.Key);
                    }
                }
            }
        }
Exemple #25
0
        public Файл ВыводОтчета(string НазваниеОтчета, string ИсходныйКод, string ИсходныйФорматОтчета, ФорматОтчета ФорматОтчета, ШаблонОтчета.Ориентация Ориентация, DataSet ds, Хранилище Хранилище, string user, string domain)
        {
            var file = null as Файл;

            try
            {
                if (ds == null)
                {
                    new Exception("Не определен DataSet");
                }

                var extension = string.Empty;
                var mime      = MimeType.НеОпределен;
                switch (ИсходныйФорматОтчета)
                {
                case "Xps":
                    extension = "xps";
                    mime      = MimeType.Xps;
                    break;

                case "Excel":
                    extension = "xls";
                    mime      = MimeType.Excel;
                    break;

                case "Word":
                    extension = "doc";
                    mime      = MimeType.Word;
                    break;

                case "Text Plain":
                    extension = "txt";
                    mime      = MimeType.Text;
                    break;

                case "Excel-PDF":
                case "Word-PDF":
                    extension = "pdf";
                    break;

                default:
                    throw new Exception("Не верно указан 'Исходный формат отчета'");
                }
                file = new Файл()
                {
                    Name = string.Format("{0}_{1:yyyymmdd_HHmmss}.{2}", FileNameValid(НазваниеОтчета), DateTime.Now, extension), MimeType = mime
                };
                var task = new System.Threading.Tasks.Task(() =>
                {
                    try
                    {
                        using (var msXml = new MemoryStream())
                        {
                            var processor   = new Saxon.Api.Processor();
                            var compiler    = processor.NewXsltCompiler();
                            var transformer = compiler.Compile(new StringReader(ИсходныйКод)).Load();
                            var dest        = new Saxon.Api.TextWriterDestination(XmlTextWriter.Create(msXml));

                            transformer.InitialContextNode = processor.NewDocumentBuilder().Build(new XmlDataDocument(ds));
                            transformer.Run(dest);

                            switch (ИсходныйФорматОтчета)
                            {
                            case "Xps":
                                {
                                    file.MimeType = MimeType.Xps;
                                    switch (ФорматОтчета)
                                    {
                                        #region Отчет Xaml (по-умолчанию)
                                    case ФорматОтчета.Xaml:
                                    case ФорматОтчета.ПоУмолчанию:
                                        {
                                            file.Stream = msXml.ToArray();
                                        }
                                        break;
                                        #endregion

                                        #region Отчет Xps
                                    case ФорматОтчета.Xps:
                                    default:
                                        {
                                            var documentUri = Path.GetTempFileName();
                                            try
                                            {
                                                msXml.Position = 0;
                                                var sourceDoc  = XamlReader.Load(msXml) as IDocumentPaginatorSource;

                                                var doc = new XpsDocument(documentUri, FileAccess.Write, CompressionOption.Normal);
                                                var xsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false);
                                                var pgn = sourceDoc.DocumentPaginator;
                                                // 1cm = 38px
                                                switch (Ориентация)
                                                {
                                                case ШаблонОтчета.Ориентация.Альбом:
                                                    {
                                                        pgn.PageSize = new System.Windows.Size(29.7 * (96 / 2.54), 21 * (96 / 2.54));
                                                    }
                                                    break;

                                                case ШаблонОтчета.Ориентация.Книга:
                                                default:
                                                    {
                                                        pgn.PageSize = new System.Windows.Size(21 * (96 / 2.54), 29.7 * (96 / 2.54));
                                                    }
                                                    break;
                                                }
                                                //необходимо фиксированно указать размер колонки документа иначе при
                                                //построении часть данных будет срезано
                                                if (sourceDoc is FlowDocument)
                                                {
                                                    ((FlowDocument)sourceDoc).ColumnWidth = pgn.PageSize.Width;
                                                }
                                                xsm.SaveAsXaml(pgn);

                                                doc.Close();
                                                file.Stream = System.IO.File.ReadAllBytes(documentUri);
                                            }
                                            finally
                                            {
                                                if (System.IO.File.Exists(documentUri))
                                                {
                                                    System.IO.File.Delete(documentUri);
                                                }
                                            }
                                        }
                                        break;
                                        #endregion
                                    }
                                }
                                break;

                            case "TextPlain":
                                {
                                    file.MimeType = MimeType.Text;
                                    file.Stream   = msXml.ToArray();
                                }
                                break;

                            case "Word-PDF":
                                {
                                    #region generate
                                    object paramSourceDocPath = Path.GetTempFileName();
                                    object paramMissing       = System.Type.Missing;

                                    System.IO.File.WriteAllBytes((string)paramSourceDocPath, msXml.ToArray());
                                    if (!System.IO.File.Exists((string)paramSourceDocPath))
                                    {
                                        throw new Exception(string.Format("Исходный файл для генерации отчета не найден '{0}'", paramSourceDocPath));
                                    }

                                    var wordApplication     = null as Microsoft.Office.Interop.Word.Application;
                                    var wordDocument        = null as Document;
                                    var paramExportFilePath = GetTempFilePathWithExtension(".pdf");
                                    try
                                    {
                                        wordApplication = new Microsoft.Office.Interop.Word.Application()
                                        {
                                            DisplayAlerts = WdAlertLevel.wdAlertsNone
                                        };

                                        var paramExportFormat       = WdExportFormat.wdExportFormatPDF;
                                        var paramOpenAfterExport    = false;
                                        var paramExportOptimizeFor  = WdExportOptimizeFor.wdExportOptimizeForPrint;
                                        var paramExportRange        = WdExportRange.wdExportAllDocument;
                                        var paramStartPage          = 0;
                                        var paramEndPage            = 0;
                                        var paramExportItem         = WdExportItem.wdExportDocumentContent;
                                        var paramIncludeDocProps    = true;
                                        var paramKeepIRM            = true;
                                        var paramCreateBookmarks    = WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                                        var paramDocStructureTags   = true;
                                        var paramBitmapMissingFonts = true;
                                        var paramUseISO19005_1      = false;

                                        // Open the source document.
                                        wordDocument = wordApplication.Documents.Open(
                                            ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                                            ref paramMissing, ref paramMissing, ref paramMissing,
                                            ref paramMissing, ref paramMissing, ref paramMissing,
                                            ref paramMissing, ref paramMissing, ref paramMissing,
                                            ref paramMissing, ref paramMissing, ref paramMissing,
                                            ref paramMissing);

                                        // Export it in the specified format.
                                        if (wordDocument != null)
                                        {
                                            wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                                             paramExportFormat, paramOpenAfterExport,
                                                                             paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                                             paramEndPage, paramExportItem, paramIncludeDocProps,
                                                                             paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                                             paramBitmapMissingFonts, paramUseISO19005_1,
                                                                             ref paramMissing);
                                        }

                                        if (!System.IO.File.Exists(paramExportFilePath))
                                        {
                                            throw new Exception(string.Format("Word-PDF: Файл отчета не найден '{0}'", paramExportFilePath));
                                        }

                                        if (Enum.IsDefined(typeof(MimeType), ИсходныйФорматОтчета))
                                        {
                                            file.MimeType = (MimeType)Enum.Parse(typeof(MimeType), ИсходныйФорматОтчета);
                                        }

                                        file.Stream = System.IO.File.ReadAllBytes(paramExportFilePath);
                                    }
                                    finally
                                    {
                                        // Close and release the Document object.
                                        if (wordDocument != null)
                                        {
                                            wordDocument.Close(false, ref paramMissing, ref paramMissing);
                                            wordDocument = null;
                                        }

                                        // Quit Word and release the ApplicationClass object.
                                        if (wordApplication != null)
                                        {
                                            wordApplication.Quit(false, ref paramMissing, ref paramMissing);
                                            wordApplication = null;

                                            GC.Collect();
                                            GC.WaitForPendingFinalizers();
                                            GC.Collect();
                                        }

                                        if (System.IO.File.Exists((string)paramSourceDocPath))
                                        {
                                            System.IO.File.Delete((string)paramSourceDocPath);
                                        }
                                        if (System.IO.File.Exists(paramExportFilePath))
                                        {
                                            System.IO.File.Delete(paramExportFilePath);
                                        }

                                        //var sb = new StringBuilder();
                                        //sb.AppendLine((string)paramSourceDocPath);
                                        //sb.AppendLine(paramExportFilePath);
                                        //ConfigurationClient.WindowsLog(sb.ToString(), "", domain);
                                    }
                                    #endregion
                                }
                                break;

                            case "Excel-PDF":
                                {
                                    #region generate
                                    object paramSourceDocPath = Path.GetTempFileName();
                                    object paramMissing       = System.Type.Missing;

                                    System.IO.File.WriteAllBytes((string)paramSourceDocPath, msXml.ToArray());
                                    if (!System.IO.File.Exists((string)paramSourceDocPath))
                                    {
                                        throw new Exception(string.Format("Исходный файл для генерации отчета не найден '{0}'", paramSourceDocPath));
                                    }

                                    var excelApplication = new Microsoft.Office.Interop.Excel.Application()
                                    {
                                        DisplayAlerts = false
                                    };
                                    var excelDocument = null as Workbook;

                                    var paramExportFilePath   = GetTempFilePathWithExtension(".pdf");
                                    var paramExportFormat     = XlFixedFormatType.xlTypePDF;
                                    var paramExportQuality    = XlFixedFormatQuality.xlQualityStandard;
                                    var paramOpenAfterPublish = false;
                                    var paramIncludeDocProps  = true;
                                    var paramIgnorePrintAreas = true;
                                    var paramFromPage         = System.Type.Missing;
                                    var paramToPage           = System.Type.Missing;

                                    try
                                    {
                                        // Open the source document.
                                        excelDocument = excelApplication.Workbooks.Open(
                                            (string)paramSourceDocPath, paramMissing, paramMissing,
                                            paramMissing, paramMissing, paramMissing,
                                            paramMissing, paramMissing, paramMissing,
                                            paramMissing, paramMissing, paramMissing,
                                            paramMissing, paramMissing, paramMissing);

                                        // Export it in the specified format.
                                        if (excelDocument != null)
                                        {
                                            excelDocument.ExportAsFixedFormat(paramExportFormat,
                                                                              paramExportFilePath, paramExportQuality,
                                                                              paramIncludeDocProps, paramIgnorePrintAreas, paramFromPage,
                                                                              paramToPage, paramOpenAfterPublish,
                                                                              paramMissing);
                                        }

                                        if (!System.IO.File.Exists(paramExportFilePath))
                                        {
                                            throw new Exception(string.Format("Файл отчета не найден '{0}'", paramExportFilePath));
                                        }

                                        if (Enum.IsDefined(typeof(MimeType), ИсходныйФорматОтчета))
                                        {
                                            file.MimeType = (MimeType)Enum.Parse(typeof(MimeType), ИсходныйФорматОтчета);
                                        }

                                        file.Stream = System.IO.File.ReadAllBytes(paramExportFilePath);
                                    }
                                    finally
                                    {
                                        // Close and release the Document object.
                                        if (excelDocument != null)
                                        {
                                            excelDocument.Close(false, paramMissing, paramMissing);
                                            excelDocument = null;
                                        }

                                        // Quit Word and release the ApplicationClass object.
                                        if (excelApplication != null)
                                        {
                                            excelApplication.Quit();
                                            excelApplication = null;
                                        }

                                        if (System.IO.File.Exists((string)paramSourceDocPath))
                                        {
                                            System.IO.File.Delete((string)paramSourceDocPath);
                                        }
                                        if (System.IO.File.Exists(paramExportFilePath))
                                        {
                                            System.IO.File.Delete(paramExportFilePath);
                                        }

                                        GC.Collect();
                                        GC.WaitForPendingFinalizers();
                                        GC.Collect();
                                        GC.WaitForPendingFinalizers();
                                    }
                                    #endregion
                                }
                                break;

                            default:
                                {
                                    if (Enum.IsDefined(typeof(MimeType), ИсходныйФорматОтчета))
                                    {
                                        file.MimeType = (MimeType)Enum.Parse(typeof(MimeType), ИсходныйФорматОтчета);
                                    }

                                    file.Stream = msXml.ToArray();
                                }
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ConfigurationClient.WindowsLog(ex.ToString(), user, domain, "ВыводОтчета");
                    }
                });
                task.Start();
                task.Wait();
            }
            catch (Exception ex)
            {
                ConfigurationClient.WindowsLog(ex.ToString(), user, domain, "ВыводОтчета");
            }
            return(file);
        }
        public async Task GetBatch()
        {
            var response1 = new MockResponse(200);

            response1.SetContent(SerializationHelpers.Serialize(new []
            {
                CreateSetting(0),
                CreateSetting(1),
            }, SerializeBatch));
            response1.AddHeader(new HttpHeader("Link", $"</kv?after=5>;rel=\"next\""));

            var response2 = new MockResponse(200);

            response2.SetContent(SerializationHelpers.Serialize(new []
            {
                CreateSetting(2),
                CreateSetting(3),
                CreateSetting(4),
            }, SerializeBatch));

            var mockTransport           = new MockTransport(response1, response2);
            ConfigurationClient service = CreateTestService(mockTransport);

            var query    = new SettingSelector();
            int keyIndex = 0;

            while (true)
            {
                using (Response <SettingBatch> response = await service.GetBatchAsync(query, CancellationToken.None))
                {
                    SettingBatch batch = response.Value;
                    for (int i = 0; i < batch.Count; i++)
                    {
                        ConfigurationSetting value = batch[i];
                        Assert.AreEqual("key" + keyIndex, value.Key);
                        keyIndex++;
                    }

                    var nextBatch = batch.NextBatch;

                    if (nextBatch == null)
                    {
                        break;
                    }

                    query = nextBatch;
                }
            }

            Assert.AreEqual(2, mockTransport.Requests.Count);

            MockRequest request1 = mockTransport.Requests[0];

            Assert.AreEqual(HttpPipelineMethod.Get, request1.Method);
            Assert.AreEqual("https://contoso.azconfig.io/kv/?key=*&label=*", request1.UriBuilder.ToString());
            AssertRequestCommon(request1);

            MockRequest request2 = mockTransport.Requests[1];

            Assert.AreEqual(HttpPipelineMethod.Get, request2.Method);
            Assert.AreEqual("https://contoso.azconfig.io/kv/?key=*&label=*&after=5", request2.UriBuilder.ToString());
            AssertRequestCommon(request1);
        }
Exemple #27
0
        public Файл СформироватьОтчет(string НазваниеОтчета, Query.Параметр[] Параметры, ФорматОтчета ФорматОтчета, Хранилище Хранилище, string user, string domain)
        {
            var id_report   = FindReport(НазваниеОтчета, domain);
            var ИсходныйКод = data.ПолучитьЗначение <string>(id_report, "ИсходныйКод", Хранилище.Конфигурация, domain);
            var Запросы     = BuildQuery(Параметры, id_report, domain);

            if (string.IsNullOrEmpty(ИсходныйКод))
            {
                if (Запросы != null && Запросы.Count() > 0)
                {
                    var Шаблон = new ШаблонОтчета()
                    {
                        ВерхнийКолонтитул  = true,
                        НижнийКолонтитул   = true,
                        ОриентацияСтраницы = ШаблонОтчета.Ориентация.Альбом,
                        НазваниеОтчета     = НазваниеОтчета,
                        Запросы            = Запросы.Select(p => Serializer(p)).ToArray()
                    };
                    var колонки   = new List <ШаблонОтчета.Колонка>();
                    var firsQuery = Запросы.ElementAt(0);
                    firsQuery.Parse(domain);
                    foreach (var item in firsQuery.ВыводимыеКолонки)
                    {
                        var type = new ConfigurationClient().ПолучитьТип(item.Атрибут, domain);
                        if (type == null)
                        {
                            continue;
                        }

                        var __Колонка = new ШаблонОтчета.Колонка()
                        {
                            Атрибут = item.Атрибут, Название = type.Описание
                        };
                        switch (type.MemberType)
                        {
                        case MemberTypes.String:
                            __Колонка.азмер = 160;
                            break;

                        case MemberTypes.Double:
                        case MemberTypes.Int:
                            __Колонка.азмер = 100;
                            break;

                        case MemberTypes.DateTime:
                            __Колонка.азмер = 80;
                            break;

                        case MemberTypes.Bool:
                            __Колонка.азмер = 40;
                            break;

                        case MemberTypes.Ссылка:
                            __Колонка.азмер   = 200;
                            __Колонка.Атрибут = item.Атрибут + ".НазваниеОбъекта";
                            break;
                        }
                        колонки.Add(__Колонка);
                    }
                    Шаблон.Колонки = колонки.ToArray();
                    return(СформироватьОтчет(Шаблон, Хранилище, user, domain));
                }
                else
                {
                    return(new Файл());
                }
            }
            else
            {
                #region Подготовить DataSet
                var ds = BuildDataSet(НазваниеОтчета, Запросы, Хранилище, user, domain);
                #endregion

                return(ВыводОтчета(
                           НазваниеОтчета,
                           ИсходныйКод,
                           data.ПолучитьЗначение <string>(id_report, "ФорматОтчета", Хранилище.Конфигурация, domain),
                           ФорматОтчета,
                           (ШаблонОтчета.Ориентация)Enum.Parse(typeof(ШаблонОтчета.Ориентация), data.ПолучитьЗначение <string>(id_report, "Ориентация", Хранилище.Конфигурация, domain)),
                           ds, Хранилище, user, domain));
            }
        }
 public ConfigurationService(ConfigurationClient configurationClient, SecretClient secretClient, ILogger <ConfigurationService> logger)
 {
     this.logger = logger;
     this.configurationClient = configurationClient;
     this.secretClient        = secretClient;
 }
Exemple #29
0
        public Файл СформироватьОтчет(ШаблонОтчета Шаблон, Хранилище Хранилище, string user, string domain)
        {
            if (Шаблон.Колонки == null)
            {
                Шаблон.Колонки = new ШаблонОтчета.Колонка[0];
            }
            else
            {
                Шаблон.Колонки = Шаблон.Колонки.Where(p => !string.IsNullOrEmpty(p.Атрибут)).ToArray();
            }

            switch (Шаблон.ФорматОтчета)
            {
            //case ФорматОтчета.ПоУмолчанию:
            case ФорматОтчета.Xaml:
            case ФорматОтчета.Xps:
                throw new Exception(string.Format("Формат '{0}' не поддерживается конструктором отчетов", Шаблон.ФорматОтчета.ToString()));
            }
            var sb = new StringBuilder(10000);

            #region Подготовить DataSet
            var querys = Шаблон.Запросы.Select(p => Query.Deserialize(p)).ToArray();
            foreach (var item in querys.Where(p => p != null))
            {
                item.ИгнорироватьСтраницы = true;
            }
            var ds = BuildDataSet(Шаблон.НазваниеОтчета, querys, Хранилище, user, domain);
            #endregion

            #region generate columns
            var table = new System.Data.DataTable("Columns");
            table.Columns.Add("Атрибут", typeof(string));
            table.Columns.Add("Название", typeof(string));
            table.Columns.Add("Размер", typeof(int));
            foreach (var item in Шаблон.Колонки)
            {
                table.Rows.Add(new object[] { item.Атрибут, item.Название, !double.IsNaN(item.азмер) ? item.азмер : 140 });
            }
            ds.Merge(table);
            #endregion

            #region Columns Display
            sb = new StringBuilder();

            var source = "//Значение1";
            if (Шаблон.Группировки != null)
            {
                foreach (var item in Шаблон.Группировки)
                {
                    var _Группировки = item.Trim().Replace("/", "_x002F_").Replace("@", "_x0040_");
                    sb.AppendFormat(@"<xsl:for-each-group select=""{0}"" group-by=""{1}"">", source, _Группировки);
                    sb.AppendLine();
                    sb.AppendLine(@"<xsl:sort select=""current-grouping-key()""/>");
                    sb.AppendLine(@"<Row>");
                    sb.AppendFormat("\t<Cell ss:MergeAcross=\"{0}\" ss:StyleID=\"s177\">", Шаблон.Колонки.Length - 1);
                    sb.AppendLine();
                    sb.AppendLine("\t\t<Data ss:Type=\"String\"><xsl:value-of select=\"current-grouping-key()\"/></Data>");
                    sb.AppendLine("\t</Cell>");
                    sb.AppendLine(@"</Row>");
                    source = "current-group()";
                }
            }

            #region <Header>
            sb.Append(@"
<Row ss:Height=""13.5"">
<xsl:for-each select=""//Columns"">
    <Cell ss:StyleID=""s97"">
    <Data ss:Type=""String"">
        <xsl:value-of select=""Название"" />
    </Data>
    </Cell>
</xsl:for-each>
</Row>
");
            #endregion

            #region <Row>
            var isDataSet = ds != null && ds.Tables.Contains("Значение1");
            sb.AppendFormat(@"<xsl:for-each select=""{0}"">", source);
            sb.AppendLine(@"<Row>");
            foreach (var item in Шаблон.Колонки)
            {
                var style = "s93";
                var type  = null as Configuration.Type;
                if (!string.IsNullOrEmpty(item.Формат))
                {
                    switch (item.Формат)
                    {
                    case "Int":
                        type = new Configuration.Type()
                        {
                            MemberType = MemberTypes.Int
                        };
                        break;

                    case "Double":
                        type = new Configuration.Type()
                        {
                            MemberType = MemberTypes.Double
                        };
                        break;

                    case "String":
                        type = new Configuration.Type()
                        {
                            MemberType = MemberTypes.String
                        };
                        break;
                    }
                }

                if (type == null && isDataSet && ds.Tables["Значение1"].Columns.Contains(item.Атрибут))
                {
                    //определить тип из DataSet
                    var typeofColumn = ds.Tables["Значение1"].Columns[item.Атрибут].DataType;
                    if (typeofColumn == typeof(double) || typeofColumn == typeof(decimal))
                    {
                        type = new Configuration.Type()
                        {
                            MemberType = MemberTypes.Double
                        }
                    }
                    ;

                    else if (typeofColumn == typeof(int) || typeofColumn == typeof(long))
                    {
                        type = new Configuration.Type()
                        {
                            MemberType = MemberTypes.Int
                        }
                    }
                    ;

                    else if (typeofColumn == typeof(DateTime))
                    {
                        type = new Configuration.Type()
                        {
                            MemberType = MemberTypes.DateTime
                        }
                    }
                    ;

                    else if (typeofColumn == typeof(bool))
                    {
                        type = new Configuration.Type()
                        {
                            MemberType = MemberTypes.Bool
                        }
                    }
                    ;

                    else
                    {
                        type = new Configuration.Type()
                        {
                            MemberType = MemberTypes.String
                        }
                    };
                }
                else
                {
                    type = new ConfigurationClient().ПолучитьТип(item.Атрибут, domain);
                }

                #region set style
                if (type != null)
                {
                    switch (type.MemberType)
                    {
                    case MemberTypes.Double:
                        style = "s93Numeric";
                        break;

                    case MemberTypes.Ссылка:
                    case MemberTypes.Int:
                        style = "s93Int";
                        break;
                    }
                }
                #endregion

                sb.AppendFormat("<Cell ss:StyleID=\"{0}\">", style);
                sb.AppendLine();
                if (!string.IsNullOrEmpty(item.Атрибут))
                {
                    var attr = item.Атрибут.Replace("/", "_x002F_").Replace("@", "_x0040_");
                    if (type != null)
                    {
                        switch (type.MemberType)
                        {
                        case MemberTypes.Double:
                        case MemberTypes.Ссылка:
                        case MemberTypes.Int:
                            sb.Append(@"<Data ss:Type=""Number"">");
                            sb.AppendFormat(@"<xsl:value-of select=""{0}"" />", attr);
                            //sb.AppendFormat(@"<xsl:value-of select=""format-number({0},'# ##0,00')"" />", item.Атрибут);
                            break;

                        case MemberTypes.DateTime:
                            sb.Append(@"<Data ss:Type=""String"">");
                            switch ((item.Формат ?? "").ToUpper())
                            {
                            case "G":
                                sb.AppendFormat(@"<xsl:value-of select=""format-dateTime({0},'[D,2].[M,2].[Y,*-4] [H01]:[m01]')"" />", attr);
                                break;

                            case "HH:MM":
                                sb.AppendFormat(@"<xsl:value-of select=""format-dateTime({0},'[H01]:[m01]')"" />", attr);
                                break;

                            default:
                                sb.AppendFormat(@"<xsl:value-of select=""format-dateTime({0},'[D,2].[M,2].[Y,*-4]')"" />", attr);
                                break;
                            }
                            break;

                        //case MemberTypes.Bool:
                        //    sb.Append(@"<Data ss:Type=""String"">");
                        //    sb.AppendFormat(@"<xsl:if test=""{0} = 'true'"">ДА</<xsl:if>", attr);
                        //    break;

                        default:
                            sb.Append(@"<Data ss:Type=""String"">");
                            sb.AppendFormat(@"<xsl:value-of select=""{0}"" />", attr);
                            break;
                        }
                    }
                    else
                    {
                        sb.AppendFormat(@"<Data ss:Type=""{0}"">", item.ТипЗначения.ToString());
                        sb.AppendFormat(@"<xsl:value-of select=""{0}"" />", attr);
                    }
                    sb.AppendLine(@"</Data>");
                }
                sb.AppendLine(@"</Cell>");
            }
            sb.AppendLine(@"</Row>");
            sb.AppendLine(@"</xsl:for-each>");
            sb.AppendLine(@"<Row />");
            sb.AppendLine(@"<Row />");
            #endregion

            if (Шаблон.Группировки != null)
            {
                foreach (var item in Шаблон.Группировки)
                {
                    sb.AppendLine(@"</xsl:for-each-group>");
                }
            }
            #endregion

            #region ИсходныйКод
            var ИсходныйКод = Regex.Replace(RosService.Properties.Resources.ReportExcel, "<r:Data />", sb.ToString());
            #endregion

            return(ВыводОтчета(
                       Шаблон.НазваниеОтчета,
                       ИсходныйКод.ToString(),
                       "Excel",
                       Шаблон.ФорматОтчета,
                       Шаблон.ОриентацияСтраницы,
                       ds,
                       Хранилище,
                       user,
                       domain));
        }
        public static async Task <IEnumerable <KeyValueChange> > GetKeyValueChangeCollection(this ConfigurationClient client, IEnumerable <ConfigurationSetting> keyValues, GetKeyValueChangeCollectionOptions options, CancellationToken cancellationToken)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (keyValues == null)
            {
                keyValues = Enumerable.Empty <ConfigurationSetting>();
            }

            if (options.KeyFilter == null)
            {
                options.KeyFilter = string.Empty;
            }

            if (keyValues.Any(k => string.IsNullOrEmpty(k.Key)))
            {
                throw new ArgumentNullException($"{nameof(keyValues)}[].{nameof(ConfigurationSetting.Key)}");
            }

            if (keyValues.Any(k => !string.Equals(k.Label.NormalizeNull(), options.Label.NormalizeNull())))
            {
                throw new ArgumentException("All key-values registered for refresh must use the same label.", $"{nameof(keyValues)}[].{nameof(ConfigurationSetting.Label)}");
            }

            if (keyValues.Any(k => k.Label != null && k.Label.Contains("*")))
            {
                throw new ArgumentException("The label filter cannot contain '*'", $"{nameof(options)}.{nameof(options.Label)}");
            }

            var hasKeyValueCollectionChanged = false;
            var selector = new SettingSelector
            {
                KeyFilter   = options.KeyFilter,
                LabelFilter = string.IsNullOrEmpty(options.Label) ? LabelFilter.Null : options.Label,
                Fields      = SettingFields.ETag | SettingFields.Key
            };

            // Dictionary of eTags that we write to and use for comparison
            var eTagMap = keyValues.ToDictionary(kv => kv.Key, kv => kv.ETag);

            // Fetch e-tags for prefixed key-values that can be used to detect changes
            await TracingUtils.CallWithRequestTracing(options.RequestTracingEnabled, RequestType.Watch, options.RequestTracingOptions,
                                                      async() =>
            {
                await foreach (ConfigurationSetting setting in client.GetConfigurationSettingsAsync(selector, cancellationToken).ConfigureAwait(false))
                {
                    if (!eTagMap.TryGetValue(setting.Key, out ETag etag) || !etag.Equals(setting.ETag))
                    {
                        hasKeyValueCollectionChanged = true;
                        break;
                    }

                    eTagMap.Remove(setting.Key);
                }
            }).ConfigureAwait(false);
Exemple #31
0
        private void ConfigureOAuth(IAppBuilder app)
        {
            // Call the service to get its configuration back
            var provider = new MvcConfigurationProvider(ConfigurationManager.AppSettings);
            MvcConfiguration mvcConfiguration = provider.Load();

            var            configClient = new ConfigurationClient(mvcConfiguration.ServiceUrl);
            IConfiguration config       = configClient.GetConfiguration();

            var cookieOptions = new CookieAuthenticationOptions
            {
                LoginPath  = new PathString("/Authentication/Login"),
                CookieName = "SyringeOAuth"
            };

            app.UseCookieAuthentication(cookieOptions);

            // Only enable if there are credentials
            if (config.ContainsOAuthCredentials())
            {
                app.SetDefaultSignInAsAuthenticationType(cookieOptions.AuthenticationType);
            }


            //
            // OAuth2 Integrations
            //
            if (!string.IsNullOrEmpty(config.OAuthConfiguration.GoogleAuthClientId) &&
                !string.IsNullOrEmpty(config.OAuthConfiguration.GoogleAuthClientSecret))
            {
                // Console: https://console.developers.google.com/home/dashboard
                // Found under API and credentials.
                app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions
                {
                    ClientId     = config.OAuthConfiguration.GoogleAuthClientId,
                    ClientSecret = config.OAuthConfiguration.GoogleAuthClientSecret
                });
            }
            if (!string.IsNullOrEmpty(config.OAuthConfiguration.MicrosoftAuthClientId) &&
                !string.IsNullOrEmpty(config.OAuthConfiguration.MicrosoftAuthClientSecret))
            {
                // Console: https://account.live.com/developers/applications/
                // Make sure he 'redirecturl' is set to 'http://localhost:1980/Authentication/Noop' (or the domain being used), to match the CallbackPath
                app.UseMicrosoftAccountAuthentication(new MicrosoftAccountAuthenticationOptions()
                {
                    ClientId     = config.OAuthConfiguration.MicrosoftAuthClientId,
                    ClientSecret = config.OAuthConfiguration.MicrosoftAuthClientSecret,
                    CallbackPath = new PathString("/Authentication/Noop")
                });
            }
            if (!string.IsNullOrEmpty(config.OAuthConfiguration.GithubAuthClientId) &&
                !string.IsNullOrEmpty(config.OAuthConfiguration.GithubAuthClientSecret))
            {
                // Console:  https://github.com/settings/developers
                // Set the callback url in the Github console to the same as the homepage url.
                var githubConfig = new GitHubAuthenticationOptions()
                {
                    ClientId     = config.OAuthConfiguration.GithubAuthClientId,
                    ClientSecret = config.OAuthConfiguration.GithubAuthClientSecret,
                };

                if (config.OAuthConfiguration.ContainsGithubEnterpriseSettings())
                {
                    githubConfig.Endpoints = new GitHubAuthenticationOptions.GitHubAuthenticationEndpoints()
                    {
                        AuthorizationEndpoint = config.OAuthConfiguration.GithubEnterpriseAuthorizationEndpoint,
                        TokenEndpoint         = config.OAuthConfiguration.GithubEnterpriseTokenEndpoint,
                        UserInfoEndpoint      = config.OAuthConfiguration.GithubEnterpriseUserInfoEndpoint
                    };
                }

                app.UseGitHubAuthentication(githubConfig);
            }
        }