Beispiel #1
0
        /// <summary>
        /// Resolve URI UriTemplate with base URI and different types of arguments.
        /// </summary>
        /// <param name="baseUri">Base URI for resolving relative URI templates.</param>
        /// <param name="template">The URI UriTemplate to resolve.</param>
        /// <param name="parameters">Parameters for resolving URI UriTemplate (can be IDictionary<string, string>, NameValueCollection or
        /// any object where property names are used to match parameter names.</param>
        /// <returns></returns>
        public static Uri BindTemplate(Uri baseUri, UriTemplate template, object parameters = null)
        {
            if (baseUri == null)
            {
                throw new InvalidOperationException("It is not possible to bind relative URL templates without a base URL. Make sure session and/or service has been created with a base URL.");
            }
            Condition.Requires(template, "template").IsNotNull();

            if (parameters == null)
            {
                Dictionary <string, string> emptyParameters = new Dictionary <string, string>();
                return(template.BindByName(baseUri, emptyParameters));
            }
            else if (parameters is IDictionary <string, string> dp)
            {
                return(template.BindByName(baseUri, dp));
            }
            else if (parameters is NameValueCollection nvp)
            {
                IDictionary <string, string> dictParameters = nvp.Cast <string>().ToDictionary(p => p, p => nvp[p]);
                return(template.BindByName(baseUri, dictParameters));
            }
            else
            {
                Dictionary <string, string> parameterDictionary = DictionaryConverter.ConvertObjectPropertiesToDictionary(parameters);
                return(template.BindByName(baseUri, parameterDictionary));
            }
        }
Beispiel #2
0
    void Awake()
    {
        DontDestroyOnLoad(transform.gameObject);
        stgRef_Setup();

        tDialogueCanvas    = GameObject.FindGameObjectWithTag("testerCanvas");
        dDictionaryArchive = tDialogueCanvas.GetComponent <DictionaryConverter> ();
        dlgManager         = GameObject.FindGameObjectWithTag("DialogueManager");
        dlgInterface       = dlgManager.GetComponent <DialogueManager> ();

        Player      = GameObject.FindGameObjectWithTag("User");
        playerView  = GameObject.FindGameObjectWithTag("MainCamera").GetComponent <Camera> ();
        movementRef = Player.GetComponent <PlayerController> ();
        Prompter    = GameObject.FindGameObjectWithTag("tBox");

        assignPrmptCanvas();

        cellarLight = Player.GetComponentInChildren <LightsScript> ();
        ftTimer     = GameObject.FindGameObjectWithTag("ftTimer");
        ftTimer.SetActive(false);

        PvERef = Player.GetComponent <PlayerCombat> ();

        qStatus = Player.GetComponent <playerStatusLog> ();
        qStatus.qPhaseSet(stgRef);
        canContinue = false;
    }
        public void CanConvertSimpleObjectsToDictionary()
        {
            // Arrange
            object o1 = new { A = 10, B = "Train", C = true };
            object o2 = new SimpleObject {
                X = 10, Y = "Train", Z = true
            };

            // Act
            Dictionary <string, string> d1 = DictionaryConverter.ConvertObjectPropertiesToDictionary(o1);
            Dictionary <string, string> d2 = DictionaryConverter.ConvertObjectPropertiesToDictionary(o2);

            // Assert
            Assert.IsNotNull(d1);
            Assert.IsNotNull(d2);
            Assert.AreEqual(3, d1.Count);
            Assert.AreEqual(4, d2.Count);

            Assert.AreEqual("10", d1["A"]);
            Assert.AreEqual("Train", d1["B"]);
            Assert.AreEqual("True", d1["C"]);
            Assert.AreEqual("10", d2["X"]);
            Assert.AreEqual("Train", d2["Y"]);
            Assert.AreEqual("True", d2["Z"]);
        }
Beispiel #4
0
        public virtual Task MergeAsync(TKey key, TValue value, CancellationToken cancellationToken = default)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            var properties = DictionaryConverter.ToDictionary(value);

            if (!properties.Any())
            {
                return(TaskUtil.CompletedTask);
            }
            var existingValue = GetOrCreateValue(key);

            foreach (var propertyKeyValue in properties)
            {
                var property = typeof(TValue)
                               .GetProperty(
                    propertyKeyValue.Key,
                    BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

                if (property != null)
                {
                    try
                    {
                        if (property.PropertyType.GetTypeInfo().IsEnum)
                        {
                            property.SetValue(
                                existingValue,
                                Enum.Parse(property.PropertyType, propertyKeyValue.Value.ToString(), true));
                        }
                        else
                        {
                            property.SetValue(
                                existingValue,
                                propertyKeyValue.Value);
                        }
                    }
                    catch
                    {
                        var parse = TypeUtil.GetParseFuncForType(property.PropertyType);
                        if (parse != null)
                        {
                            property.SetValue(existingValue, parse(propertyKeyValue.Value.ToString()));
                        }
                        else
                        {
                            throw new InvalidOperationException($"Cannot set value for property '{property.Name}'");
                        }
                    }
                }
            }

            return(Task.CompletedTask);
        }
Beispiel #5
0
        private void SelectMultipleRowWithSpecifiedIds <T>()
            where T : IEnumerable <Tuple <string, bool, int, TestDataItemToFill> >
        {
            //ARRANGE
            const string queryText = @"select NVarchar50, Bit, Int, *
                                 from dbo.TestDbType 
                                 where id = @id1 or id = @id2
                                 order by id asc";

            //ACT
            var result      = Query.Select <T>(queryText, new { id1 = TestData.Item1.Id, id2 = TestData.Item2.Id });
            var resultArray = result.ToArray();

            //ASSERT
            Assert.AreEqual(2, resultArray.Length);

            Assert.AreEqual(resultArray[0].Item1, TestData.Item1.NVarchar50);
            Assert.AreEqual(resultArray[0].Item2, TestData.Item1.Bit);
            Assert.AreEqual(resultArray[0].Item3, TestData.Item1.Int);

            var actualDictionary1 = DictionaryConverter.ConvertToDictionary(resultArray[0].Item4);

            DictionaryComparator.Compare(TestData.Item1Dictionary, actualDictionary1);

            Assert.AreEqual(resultArray[1].Item1, TestData.Item2.NVarchar50);
            Assert.AreEqual(resultArray[1].Item2, TestData.Item2.Bit);
            Assert.AreEqual(resultArray[1].Item3, TestData.Item2.Int);

            var actualDictionary2 = DictionaryConverter.ConvertToDictionary(resultArray[1].Item4);

            DictionaryComparator.Compare(TestData.Item2Dictionary, actualDictionary2);
        }
Beispiel #6
0
        public void SelectMultipleTablesWithSingleRowWithSpecifiedIds()
        {
            //ARRANGE
            const string queryText = @"select * 
                                 from dbo.TestDbType 
                                 where id = @id1;
                                 
                                 select * 
                                 from dbo.TestDbType 
                                 where id = @id2;";
            //ACT
            var result = Query.Select <DataSet>(queryText, new { id1 = TestData.Item1.Id, id2 = TestData.Item2.Id });

            //ASSERT
            Assert.AreEqual(2, result.Tables.Count);
            Assert.AreEqual(1, result.Tables[0].Rows.Count);
            Assert.AreEqual(1, result.Tables[1].Rows.Count);

            var expected = new[] { TestData.Item1Dictionary, TestData.Item2Dictionary };

            var actual = new[]
            {
                DictionaryConverter.ConvertToDictionary(result.Tables[0].Rows[0]),
                DictionaryConverter.ConvertToDictionary(result.Tables[1].Rows[0])
            };

            DictionaryComparator.Compare(expected, actual);
        }
Beispiel #7
0
        static Converter()
        {
            IsSealed = typeof(T).GetTypeInfo().IsSealed || typeof(T) == typeof(Type);

            (WriteAction, ReadAction) = typeof(T) switch
            {
                Type type when type == typeof(Type) => TypeConverter.GetActions <T>(),
                Type type when type.IsAbstract() => (null, null),
                Type type when type.IsArray => ArrayConverter.GetActions <T>(),
                Type type when type.IsList() => ListConverter.GetActions <T>(),
                Type type when type.IsDictionary() => DictionaryConverter.GetActions <T>(),
                Type type when type.IsEnum() => EnumConverter.GetActions <T>(),
                Type type when type == typeof(char) => GetActions((StreamWriterWrapper w, in char v) => w.Stream.WriteLine(v), s => s[0]),
                Type type when type == typeof(bool) => GetActions((StreamWriterWrapper w, in bool v) => w.Stream.WriteLine(v), bool.Parse),
                Type type when type == typeof(sbyte) => GetActions((StreamWriterWrapper w, in sbyte v) => w.Stream.WriteLine(v), i => sbyte.Parse(i)),
                Type type when type == typeof(byte) => GetActions((StreamWriterWrapper w, in byte v) => w.Stream.WriteLine(v), i => byte.Parse(i)),
                Type type when type == typeof(short) => GetActions((StreamWriterWrapper w, in short v) => w.Stream.WriteLine(v), i => short.Parse(i)),
                Type type when type == typeof(ushort) => GetActions((StreamWriterWrapper w, in ushort v) => w.Stream.WriteLine(v), i => ushort.Parse(i)),
                Type type when type == typeof(int) => GetActions((StreamWriterWrapper w, in int v) => w.Stream.WriteLine(v), i => int.Parse(i)),
                Type type when type == typeof(uint) => GetActions((StreamWriterWrapper w, in uint v) => w.Stream.WriteLine(v), i => uint.Parse(i)),
                Type type when type == typeof(long) => GetActions((StreamWriterWrapper w, in long v) => w.Stream.WriteLine(v), i => long.Parse(i)),
                Type type when type == typeof(ulong) => GetActions((StreamWriterWrapper w, in ulong v) => w.Stream.WriteLine(v), i => ulong.Parse(i)),
                Type type when type == typeof(decimal) => GetActions((StreamWriterWrapper w, in decimal v) => w.Stream.WriteLine(v), i => decimal.Parse(i)),
                Type type when type == typeof(double) => GetActions((StreamWriterWrapper w, in double v) => w.Stream.WriteLine(v), i => double.Parse(i)),
                Type type when type == typeof(float) => GetActions((StreamWriterWrapper w, in float v) => w.Stream.WriteLine(v), i => float.Parse(i)),
                Type type when type == typeof(string) => StringConverter.GetActions <T>(),
                Type type when type == typeof(Guid) => GuidConverter.GetActions <T>(),
                _ => ObjectConverter <T> .GetActions()
            };
        }
Beispiel #8
0
        private void ChooseGroupsForm_Load(object sender, EventArgs e)
        {
            int i = 0;

            ListGroups.Items.Clear();

            List <ScheduleGroup> Groups = DictionaryConverter.GroupsToList(ds);

            foreach (ScheduleGroup group in Groups)
            {
                ListGroups.Items.Add(group.Name);
                ListGroups.SetItemChecked(i, false);
                i++;
            }

            BindingSource bs = new BindingSource();

            bs.DataSource = ScheduleView.BasicViews;
            //  cmbProjection.DisplayMember = "Description";
            // cmbProjection.ValueMember = "TypeCode";
            //  cmbProjection.DataSource = bs;

            //  ChooseView =  (View)Convert.ToInt32(cmbProjection.SelectedValue);

            //   this.cmbProjection.SelectedIndexChanged += new EventHandler(cmbProjection_SelectedIndexChanged);
        }
        private void SelectMultipleRowWithSpecifiedIds <T>()
            where T : IEnumerable <TestDataItemToFill>
        {
            //ARRANGE
            const string queryText = @"select * 
                                 from dbo.TestDbType 
                                 where id = @id1 or id = @id2
                                 order by id asc";

            //ACT
            var result      = Query.Select <T>(queryText, new { id1 = TestData.Item1.Id, id2 = TestData.Item2.Id });
            var resultArray = result.ToArray();

            //ASSERT
            Assert.IsInstanceOf <T>(result);
            Assert.AreEqual(2, resultArray.Length);

            var dictionaryResult = new[]
            {
                DictionaryConverter.ConvertToDictionary(resultArray[0]),
                DictionaryConverter.ConvertToDictionary(resultArray[1])
            };

            var expectedResult = new[] { TestData.Item1Dictionary, TestData.Item2Dictionary };

            DictionaryComparator.Compare(expectedResult, dictionaryResult);
        }
Beispiel #10
0
        private void tbsTeachers_Click(object sender, EventArgs e)
        {
            TeachersForm frmTeacher = new TeachersForm();

            frmTeacher.ds = ScheduleDataSet;
            frmTeacher.ShowDialog();
            Teachers = DictionaryConverter.TeachersToList(frmTeacher.ds);
        }
Beispiel #11
0
        private void tsbEducationLoad_Click(object sender, EventArgs e)
        {
            EdicationLoadForm frmEdicationLoad = new EdicationLoadForm(Teachers, Disciplines);

            frmEdicationLoad.SheduleDataSet = ScheduleDataSet;
            frmEdicationLoad.ShowDialog();
            EducationAdapter = new EducationLoadAdapter(DictionaryConverter.EducationToList(frmEdicationLoad.SheduleDataSet));
        }
Beispiel #12
0
        private void tsbRooms_Click(object sender, EventArgs e)
        {
            RoomsForm frmRoom = new RoomsForm();

            frmRoom.ds = ScheduleDataSet;
            frmRoom.ShowDialog();
            Rooms = DictionaryConverter.RoomsToList(frmRoom.ds);
        }
Beispiel #13
0
        public void Test_Create_empty_Dictionary(string dictionaryString)
        {
            var cut = new DictionaryConverter();

            var actual = cut.ToDictionary(dictionaryString);

            Assert.Equal(new Dictionary <string, string>(), actual);
        }
Beispiel #14
0
        private void tsbDisciplines_Click(object sender, EventArgs e)
        {
            DisciplineForm frmDiscipline = new DisciplineForm();

            frmDiscipline.ds = ScheduleDataSet;
            frmDiscipline.ShowDialog();
            Disciplines = DictionaryConverter.DisciplinesToList(frmDiscipline.ds);
        }
Beispiel #15
0
        private void tsbGroups_Click(object sender, EventArgs e)
        {
            GroupForm frmGroup = new GroupForm();

            frmGroup.ds = ScheduleDataSet;
            frmGroup.ShowDialog();
            Groups = DictionaryConverter.GroupsToList(frmGroup.ds);
        }
Beispiel #16
0
        public void Test_throw_exception(string dictionaryString)
        {
            var cut = new DictionaryConverter();

            var actual = Assert.Throws <ArgumentOutOfRangeException>(() =>
                                                                     cut.ToDictionary(dictionaryString));

            Assert.Contains(dictionaryString, actual.Message);
        }
Beispiel #17
0
        /// <summary>
        /// Log a timed event with parameters. Log a timed event with parameters with the
        /// Flurry service. To end the timer, call endTimedEvent(String) with this eventId.
        /// </summary>
        /// <param name="eventId">The name/id of the event.</param>
        /// <param name="parameters">
        /// A Dictionary of parameters to log with this event.
        /// </param>
        /// <param name="timed">True if this event is timed, false otherwise.</param>
        public static void LogEvent(string eventId, Dictionary <string, string> parameters, bool timed)
        {
#if UNITY_ANDROID && !UNITY_EDITOR
            using (DictionaryConverter converter = new DictionaryConverter(parameters))
            {
                FlurryAgent.CallStatic <AndroidJavaObject>("logEvent", eventId, (AndroidJavaObject)converter, timed);
            }
#endif
        }
Beispiel #18
0
        /// <summary>
        /// Add origin attribution with parameters.
        /// </summary>
        /// <param name="originName">
        /// The name/id of the origin you wish to attribute.
        /// </param>
        /// <param name="originVersion">
        /// The version of the origin you wish to attribute.
        /// </param>
        /// <param name="originParameters">
        /// Add origin attribution with parameters.
        /// </param>
        public static void AddOrigin(string originName, string originVersion, Dictionary <string, string> originParameters)
        {
#if UNITY_ANDROID && !UNITY_EDITOR
            using (DictionaryConverter converter = new DictionaryConverter(originParameters))
            {
                FlurryAgent.CallStatic("addOrigin", originName, originVersion, (AndroidJavaObject)converter);
            }
#endif
        }
Beispiel #19
0
        /// <summary>
        /// End a timed event.
        /// </summary>
        /// <param name="eventId">The name/id of the event to end the timer on.</param>
        /// <param name="parameters">
        /// A Dictionary of parameters to log with this event.
        /// </param>
        public static void EndTimedEvent(string eventId, Dictionary <string, string> parameters)
        {
#if UNITY_ANDROID && !UNITY_EDITOR
            using (DictionaryConverter converter = new DictionaryConverter(parameters))
            {
                FlurryAgent.CallStatic("endTimedEvent", eventId, (AndroidJavaObject)converter);
            }
#endif
        }
Beispiel #20
0
        public override object ConvertTo(CultureInfo culture, string format, object value, Type to)
        {
            // Dict > Obj
            if (value is IDictionary <string, object> dict)
            {
                return(DictionaryConverter.CreateAndPopulate(to, dict, out _));
            }

            return(base.ConvertTo(culture, format, value, to));
        }
Beispiel #21
0
 public static IValueConverter FromDictionary(IDictionary dictionary, object defaultValue)
 {
     if (_cachedConverters.TryGetValue(dictionary, out var converter))
     {
         return(converter);
     }
     converter = new DictionaryConverter(dictionary, defaultValue);
     _cachedConverters.Add(dictionary, converter);
     return(converter);
 }
        public void WhenConvertingNullItReturnsEmptyDictionary()
        {
            // Arrange

            // Act
            Dictionary <string, string> d = DictionaryConverter.ConvertObjectPropertiesToDictionary(null);

            // Assert
            Assert.IsNotNull(d);
            Assert.AreEqual(0, d.Count);
        }
        private List <CustomerViewModel> ParseResponse(List <Dictionary <string, string> > dataDictionary)
        {
            List <CustomerViewModel> customers = new List <CustomerViewModel>();

            foreach (var item in dataDictionary)
            {
                customers.Add(
                    DictionaryConverter.DictionaryToObject <CustomerViewModel>(item));
            }

            return(customers);
        }
Beispiel #24
0
        public void Test_Create_Dictionary_with_one_entry(string dictionaryString, string expected)
        {
            var cut = new DictionaryConverter();

            var dic = cut.ToDictionary(dictionaryString);

            var length = dictionaryString.IndexOf("=", StringComparison.Ordinal);
            var key    = dictionaryString.Substring(0, length);

            var actual = dic[key];

            Assert.Equal(expected, actual);
        }
Beispiel #25
0
        public void Write(object value, StringBuilder writer)
        {
            if (value != null)
            {
                var type = value.GetType();

                if (converters.TryGetValue(type, out IJsonConverter converter))
                {
                    converter.Write(value, writer);
                }
                else if (type.IsArray)
                {
                    var arrayConverter = new ArrayConverter(converters);

                    arrayConverter.Write(value, writer);
                }
                else if (type.IsGenericType)
                {
                    var typeDefinition = type.GetGenericTypeDefinition();

                    if (typeDefinition == typeof(List <>))
                    {
                        var listconverter = new ListConverter(converters);

                        listconverter.Write(value, writer);
                    }
                    else if (typeDefinition == typeof(Dictionary <,>))
                    {
                        var dictConverter = new DictionaryConverter(converters);

                        converter.Write(value, writer);
                    }
                    else
                    {
                        writer.Append(JsonConvert.NullString);
                    }
                }
                else
                {
                    var objectConverter = new ObjectConverter(converters);

                    objectConverter.Write(value, writer);
                }
            }
            else
            {
                writer.Append(JsonConvert.NullString);
            }
        }
        public void SelectSingleNullRow()
        {
            //ARRANGE
            const string queryText = @"select * 
                                 from dbo.TestDbType 
                                 where id = @id";

            //ACT
            var result = Query.Select <TestDataItemToFill>(queryText, new { id = TestData.NullItem.Id });

            //ASSERT
            var dictionaryResult = DictionaryConverter.ConvertToDictionary(result);

            DictionaryComparator.Compare(TestData.NullItemDictionary, dictionaryResult);
        }
Beispiel #27
0
        public void TestDictionaryConverterTo()
        {
            // ARRANGE
            Dictionary <string, long> dict = new Dictionary <string, long>()
            {
                { "1", 2 }, { "3", 4 }
            };
            DictionaryConverter <string, long> converter = new DictionaryConverter <string, long>();

            // ACT
            DynamoDBEntry entry = converter.ToEntry(dict);

            // ASSERT
            Assert.Equal("{\"1\":2,\"3\":4}", entry.AsString());
        }
        public void WhenConvertingDictionaryItReturnsIt()
        {
            // Arrange
            Dictionary <string, string> d1 = new Dictionary <string, string>();

            d1["W"] = "Window";

            // Act
            Dictionary <string, string> d2 = DictionaryConverter.ConvertObjectPropertiesToDictionary(d1);

            // Assert
            Assert.IsNotNull(d2);
            Assert.AreEqual(1, d2.Count);
            Assert.AreEqual("Window", d2["W"]);
        }
        public static object ToObject(this IDictionary <string, object> values, Type objectType)
        {
            Guard.NotEmpty(values, nameof(values));
            Guard.NotNull(objectType, nameof(objectType));

            if (!DictionaryConverter.CanCreateType(objectType))
            {
                throw Error.Argument(
                          "objectType",
                          "The type '{0}' must be a class and have a parameterless default constructor in order to deserialize properly.",
                          objectType.FullName);
            }

            return(DictionaryConverter.SafeCreateAndPopulate(objectType, values));
        }
Beispiel #30
0
        public void SelectSingleNullRow()
        {
            //ARRANGE
            const string queryText = @"select * 
                                 from dbo.TestDbType 
                                 where id = @id";

            //ACT
            var result = Query.Select <DataTable>(queryText, new { id = TestData.NullItem.Id });


            //ASSERT
            Assert.AreEqual(1, result.Rows.Count);
            var actual = DictionaryConverter.ConvertToDictionary(result.Rows[0]);

            DictionaryComparator.Compare(TestData.DbNullItemDictionary, actual);
        }
 /// <summary>Creates an instance for the default language.</summary>
 /// <param name="continentId">The continent identifier.</param>
 /// <returns>A repository.</returns>
 public IFloorRepository ForDefaultCulture(int continentId)
 {
     var pointOfInterestConverterFactory = new PointOfInterestConverterFactory();
     var vector2DConverter = new Vector2DConverter();
     var rectangleConverter = new RectangleConverter(vector2DConverter);
     var pointOfInterestConverter = new PointOfInterestConverter(pointOfInterestConverterFactory, vector2DConverter);
     var pointOfInterestCollectionConverter = new CollectionConverter<PointOfInterestDTO, PointOfInterest>(pointOfInterestConverter);
     var renownTaskConverter = new RenownTaskConverter(vector2DConverter);
     var renownTaskCollectionConverter = new CollectionConverter<RenownTaskDTO, RenownTask>(renownTaskConverter);
     var skillChallengeConverter = new SkillChallengeConverter(vector2DConverter);
     var skillChallengeCollectionConverter = new CollectionConverter<SkillChallengeDTO, SkillChallenge>(skillChallengeConverter);
     var outputConverter = new SectorConverter(vector2DConverter);
     var sectorCollectionConverter = new CollectionConverter<SectorDTO, Sector>(outputConverter);
     var subregionConverter = new SubregionConverter(rectangleConverter, pointOfInterestCollectionConverter, renownTaskCollectionConverter, skillChallengeCollectionConverter, sectorCollectionConverter);
     var keyValuePairConverter = new SubregionKeyValuePairConverter(subregionConverter);
     var subregionKeyValuePairConverter = new DictionaryConverter<string, SubregionDTO, int, Subregion>(keyValuePairConverter);
     var regionConverter = new RegionConverter(vector2DConverter, subregionKeyValuePairConverter);
     var regionKeyValuePairConverter = new RegionKeyValuePairConverter(regionConverter);
     var regionCollectionConverter = new DictionaryConverter<string, RegionDTO, int, Region>(regionKeyValuePairConverter);
     var size2DConverter = new Size2DConverter();
     var floorConverter = new FloorConverter(size2DConverter, rectangleConverter, regionCollectionConverter);
     return new FloorRepository(continentId, this.serviceClient, floorConverter);
 }
Beispiel #32
0
        //public static void Export2CSV(DataGrid dtGrid, IEnumerable ItemsSource,string fileName)
        //{ 
        //    string csvStr = ConverDataSet2CSV(dtGrid,ItemsSource);
        //    if(csvStr=="") return;
        //    FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
        //    //将string转换成byte[]
        //    byte[] csvArray = System.Text.Encoding.UTF8.GetBytes(csvStr.ToCharArray(), 0, csvStr.Length - 1);
        //    fs.Write(csvArray,0,csvStr.Length - 1);
        //    fs.Close();
        //    fs = null;
        //}

        ///// <summary>
        ///// 将指定的数据集中指定的表转换成CSV字符串
        ///// </summary>
        ///// <param name="dataGrid"></param>
        ///// <param name="tableName"></param>
        ///// <returns></returns>
        //private static string ConverDataSet2CSV(DataGrid dataGrid, IEnumerable ItemsSource)
        //{
        //    //首先判断数据集中是否包含指定的表
        //    if (dataGrid == null || dataGrid.ItemsSource==null)
        //    {
        //        MessageBox.Show("指定的数据集为空或不包含要写出的数据表!");
        //        return "";
        //    }
        //    string csvStr = "";
        //    //下面写出数据
        //    //DataTable tb = dataGrid.Tables[tableName];
        //    //写表名
        //    //csvStr += tb.TableName + "\n";
        //    //第一步:写出列名

        //    foreach (var column in dataGrid.Columns)
        //    {
        //        if(column is DataGridTextColumn)
        //        {
        //            DataGridTextColumn item=column as DataGridTextColumn;
        //            csvStr += "\""+column.Header.ToString() +"\"" +",";
        //        }
        //    }
        //    //去掉最后一个","
        //    csvStr = csvStr.Remove(csvStr.LastIndexOf(","), 1);
        //    csvStr += "\n";

        //    //第二步:写出数据
        //    foreach (var row in ItemsSource)
        //    {
        //        if(row is DateTime)
        //        {
        //            CustomDateConverter converter=new CustomDateConverter();
        //            converter.Convert(row,"DATE");
        //        }
        //        foreach (DataColumn column in tb.Columns)
        //        {
        //            csvStr += "\"" + row[column].ToString() + "\"" + ",";
        //        }
        //        csvStr = csvStr.Remove(csvStr.LastIndexOf(","), 1);
        //        csvStr += "\n";
        //    }
        //    return csvStr;
        //}

        #endregion


        /// <summary>        
        /// 导出DataGrid数据到Excel        
        /// </summary>        
        /// <param name="withHeaders">是否需要表头</param>        
        /// <param name="grid">DataGrid</param>        
        /// <returns>Excel内容字符串</returns>        
        public static string ExportDataGrid(bool withHeaders, DataGrid grid)
        {
            System.Reflection.PropertyInfo propInfo;
            System.Windows.Data.Binding binding;
            var strBuilder = new System.Text.StringBuilder();
            DictionaryConverter dicConverter = new DictionaryConverter();
            var source = (grid.ItemsSource as System.Collections.IList);
            if (source == null) return "";
            var headers = new List<string>();
            grid.Columns.ForEach(col =>
            {
                if (col is DataGridBoundColumn)
                {
                    string strHeader = ConvertDic(col.Header.ToString());
                    headers.Add(FormatCsvField(strHeader));
                }
            });
            strBuilder.Append(String.Join(",", headers.ToArray())).Append("\r\n");
            foreach (Object data in source)
            {
                var csvRow = new List<string>();
                foreach (DataGridColumn col in grid.Columns)
                {
                    try
                    {
                        if (col is DataGridBoundColumn)
                        {
                            binding = (col as DataGridBoundColumn).Binding;
                            string colPath = binding.Path.Path;
                            string[] arr = colPath.Split('.');
                            string dicCategory = Convert.ToString(binding.ConverterParameter);//如有绑定字典值,则为字典类别
                            propInfo = data.GetType().GetProperty(colPath);
                            object ob = data;
                            if (arr.Length > 1)
                            {
                                ob = data.GetObjValue(arr[0]);
                                propInfo = data.GetObjValue(arr[0]).GetType().GetProperty(arr[1]);
                            }
                            if (propInfo != null)
                            {
                                object obj = propInfo.GetValue(ob, null) == null ? null : propInfo.GetValue(ob, null).ToString();
                                obj = dicConverter.Convert(obj, null, dicCategory, null);
                                string value = Convert.ToString(obj);
                                csvRow.Add(FormatCsvField(value));
                            }
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
                strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\r\n");
            }
            return strBuilder.ToString();
        }