Friday 29 September 2017

remove whitespace from string in C#

public static string RemoveWhitespace(string input)
        {
            return new string(input.ToCharArray()
                .Where(c => !Char.IsWhiteSpace(c))
                .ToArray());
        }

truncate string from specified length


        public static string TruncateString(string str, int maxLength)
        {
            return str.Substring(0, Math.Min(str.Length, maxLength));
        }

split string based on substring



        public string GetAlignStyle(List<string> results, string content)
        {
            var stringResult = "";
            var abc = results.Find(x => x.Contains(content));
            if (abc != null)
            {
                var index = results.FindIndex(x => x.Contains(content));
                var styleString = results[index].Split(new string[] {"text-align:"}, StringSplitOptions.None);
                if (styleString.Length > 1)
                {
                    stringResult = TruncateLongString(styleString[1].Trim(), 4);
                    results.RemoveAt(index);
                }
            }
            return stringResult;
        }

Friday 8 September 2017

handle max json length propert in C#

Step1 : set in webconfig file:
 <add key="aspnet:MaxJsonDeserializerMembers" value="550000"/>


______________________________________________________________

Step2: add in app_start folder

 public sealed class CustomJsonValueProviderFactory : ValueProviderFactory
    {
        public override IValueProvider GetValueProvider(ControllerContext controllerContext)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

            var jsonData = GetDeserializedObject(controllerContext);
            if (jsonData == null)
            {
                return null;
            }

            var backingStore = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
            var backingStoreWrapper = new EntryLimitedDictionary(backingStore);
            AddToBackingStore(backingStoreWrapper, String.Empty, jsonData);
            return new DictionaryValueProvider<object>(backingStore, CultureInfo.CurrentCulture);
        }

        private static void AddToBackingStore(EntryLimitedDictionary backingStore, string prefix, object value)
        {
            var d = value as IDictionary<string, object>;
            if (d != null)
            {
                foreach (var entry in d)
                {
                    AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);
                }
                return;
            }

            var l = value as IList;
            if (l != null)
            {
                for (var i = 0; i < l.Count; i++)
                {
                    AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]);
                }
                return;
            }

            // primitive
            backingStore.Add(prefix, value);
        }

        private static object GetDeserializedObject(ControllerContext controllerContext)
        {
            if (
                !controllerContext.HttpContext.Request.ContentType.StartsWith("application/json",
                    StringComparison.OrdinalIgnoreCase))
            {
                // not JSON request
                return null;
            }

            var reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
            var bodyText = reader.ReadToEnd();
            if (String.IsNullOrEmpty(bodyText))
            {
                // no JSON data
                return null;
            }

            var serializer = new JavaScriptSerializer {MaxJsonLength = int.MaxValue};

            var jsonData = serializer.DeserializeObject(bodyText);
            return jsonData;
        }

        private static string MakeArrayKey(string prefix, int index)
        {
            return prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
        }

        private static string MakePropertyKey(string prefix, string propertyName)
        {
            return (String.IsNullOrEmpty(prefix)) ? propertyName : prefix + "." + propertyName;
        }

        private class EntryLimitedDictionary
        {
            private readonly IDictionary<string, object> _innerDictionary;
            private int _itemCount;

            public EntryLimitedDictionary(IDictionary<string, object> innerDictionary)
            {
                _innerDictionary = innerDictionary;
            }

            public void Add(string key, object value)
            {
                if (++_itemCount > MaximumDepth)
                {
                    throw new InvalidOperationException(
                        "The length of the string exceeds the value set on the maxJsonLength property.");
                }

                _innerDictionary.Add(key, value);
            }

            private static int GetMaximumDepth()
            {
                var appSettings = ConfigurationManager.AppSettings;

                var valueArray = appSettings.GetValues("aspnet:MaxJsonDeserializerMembers");
                if (valueArray != null && valueArray.Length > 0)
                {
                    int result;
                    if (Int32.TryParse(valueArray[0], out result))
                    {
                        return result;
                    }
                }

                return 1000; // Fallback default
            }

            private static readonly int MaximumDepth = GetMaximumDepth();
        }
    }


________________________________________________

step3: add in global.asax under protected void Application_Start()
        {



 // Increase max Json length
            foreach (var factory in ValueProviderFactories.Factories)
            {
                if (factory is JsonValueProviderFactory)
                {
                    ValueProviderFactories.Factories.Remove(factory as JsonValueProviderFactory);
                    break;
                }
            }
            ValueProviderFactories.Factories.Add(new CustomJsonValueProviderFactory());

}


convert from list to datatable in C#

DataTable employeeDt = employeeList.ConvertToDataTable();
________________________________________________________________
  1. public static DataTable ConvertToDataTable<T>(List<T> list)  
  2. {  
  3. DataTable tempDt = new DataTable(typeof(T).Name);  
  4.   
  5. //return all properties  
  6. var [] propInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);  
  7. foreach (var prop in propInfo)  
  8. {  
  9. //defining type  
  10. var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);  
  11. //set the column name  
  12. tempDt.Columns.Add(prop.Name, type);  
  13. }  
  14. foreach (var item in list)  
  15. {  
  16. var values = new object[propInfo.Length];  
  17. for (int i = 0; i < propInfo.Length; i++)  
  18. {  
  19. //prepare for datatable  
  20. values[i] = propInfo[i].GetValue(item, null);  
  21. }  
  22. tempDt .Rows.Add(values);  
  23. }  
  24. return dataTable;  
  25. }  
_______________________________________________________________________________________________
 Convert from IEnumerable to datatable in C#
  1. public static DataTable ConvertToDataTable<T>(this IEnumerable<T> dataCollection)  
  2.     {  
  3.         PropertyDescriptorCollection propertiesDC =  
  4.             TypeDescriptor.GetProperties(typeof(T));  
  5.         DataTable dt = new DataTable();  
  6.         foreach (var item in propertiesDC)  
  7.             dt.Columns.Add(prop.Name, Nullable.GetUnderlyingType(item.PropertyType) ?? item.PropertyType);  
  8.         foreach (var row in dataCollection)  
  9.         {  
  10.             DataRow r = table.NewRow();  
  11.             foreach (var p in propertiesDC)  
  12.                 r[p.Name] = p.GetValue(item) ?? DBNull.Value;  
  13.             table.Rows.Add(r);  
  14.         }  
  15.         return dt;  
  16.     }  
_____________________________________________________________________
Create dataTable in C#
  1. var myTable = new DataTable();  
  2.             myTable.Columns.Add("Id", typeof(int));             
  3.             myTable.Columns.Add("Name", typeof(string));  

bulk insert in sql

// prepare your table

 var recipientTable = new DataTable();
            recipientTable.Columns.Add("Id", typeof(int));
            recipientTable.Columns.Add("MId", typeof(int));
            recipientTable.Columns.Add("CGuid", typeof(Guid));
            recipientTable.Columns.Add("DId", typeof(int));
            recipientTable.Columns.Add("PId", typeof(int));
            recipientTable.Columns.Add("CId", typeof(int));
            recipientTable.Columns.Add("Status", typeof(int));
            recipientTable.Columns.Add("Name", typeof(string));
            recipientTable.Columns.Add("UToken", typeof(Guid));
            recipientTable.Columns.Add("PDate", typeof(DateTime));
            recipientTable.Columns.Add("MProperties", typeof(string));


 // Step1  TODO :count total record,
            // step2 devide it by 2000,
            // step3  loop through it by 2000 chunk  add it recipientTable, and execute query
         
 int commitBatchSize = 2000;


 IEnumerable<Employees> recipientTableTypes = employees as Employees[] ?? employees.ToArray();

            employees.ForEach(r => recipientTable.Rows.Add(null, r.Id, null, r.Status, r.DId, null,
                                                                    r.CId, r.Name, null, DateTime.UtcNow, r.MailingProperties));

            int numberOfPages = (recipientTable.Rows.Count / commitBatchSize) + (recipientTable.Rows.Count % commitBatchSize == 0 ? 0 : 1);
            for (int pageIndex = 0; pageIndex < numberOfPages; pageIndex++)
            {
                DataTable dt = recipientTable.AsEnumerable().Skip(pageIndex * commitBatchSize).Take(commitBatchSize).CopyToDataTable();
                BulkInsert(dt, connectionString);
            }


_______________________________________________________
Method:


 public void BulkInsert(DataTable dt, string connectionString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                // make sure to enable triggers
                SqlBulkCopy bulkCopy = new SqlBulkCopy(connection,
                                                       SqlBulkCopyOptions.TableLock | SqlBulkCopyOptions.FireTriggers | SqlBulkCopyOptions.UseInternalTransaction,
                                                        null
                                                      );
                // set the destination table name
                bulkCopy.DestinationTableName = "MailingListRecipientHistory";
                connection.Open();
                // write the data in the "dataTable"
                bulkCopy.WriteToServer(dt);
                connection.Close();
            }
            // reset
            //dt.Clear();
        }






foreach loop in angularjs

var mapAuditDescription = function (auditList) {
        angular.forEach(auditList, function (row) {
            var action = row.AuditAction == "Add" ? row.AuditAction + "ed" : row.AuditAction + "d";
            var tempDescription = " " + action + " " + row.AuditTarget + " " + row.EntityName + " (ID " + row.EntityId + ").";
            row.AuditDescription = row.UserName != null && row.UserName !="" ? row.UserName + " " + tempDescription : row.SourceName + " " + tempDescription;

        });
    }



Tuesday 5 September 2017

return max json length data

 var json = Json(records, JsonRequestBehavior.AllowGet);
                json.MaxJsonLength = int.MaxValue;
                return json;