Monday, April 20, 2020

Split CSV files c#

Splitting logic of a CSV files into n number of files with .csv extension

Code Snippet:
for (int i = 1; i <= noOfFiles; i++)
{
    take = i == 1 ? finsPerCsv + mod : finsPerCsv;
    var fins = AllFins.GetRange(beginIndex, take);
    groupByfins.Add(fins);

    List<string> listw = masterData_raw.Where(item => col1Data.Any(category => category.col1.Equals(CSVParser2.Split(item)[0].Replace("\"", ""))));
    List<Items> list = masterData_cls.Where(item => col1Data.Any(category => category.col1.Equals(item.col1)));
   var csvFormattedData = list.Select(str =>
   "\"" + str.col1
   + "\",\"" + str.col2
   + "\",\"" + str.col3
   + "\",\"" + str.col4
   + "\",\"" + str.col5)
       .ToArray();
   csvHeader.CopyTo(csvFormattedData, 0);
   File.WriteAllLines(filepath, csvFormattedData);

   beginIndex = beginIndex + take;
}


Read CSV File c#

File Class - It is having methods for creation, copying, deletion, moving and opening of a single file.

Code Snippet:
List<string> masterDataList = File.ReadLines(filepath).ToList();

System.Text.RegularExpressions.Regex CSVParser = new System.Text.RegularExpressions.Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");

var columnData = masterDataList.Select(line =>
{
    String[] split = CSVParser.Split(line);
    string column = split[6].Replace("\"", "");
    return column;
}).ToList<string>();




Scenarios

var masterList = File.ReadLines(filePath).ToList();
System.Text.RegularExpressions.Regex CSVParser = new System.Text.RegularExpressions.Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
List<Items> items_MasterData = File.ReadLines(filePath).Select(line =>
{
Items ch = new Items();
System.Text.RegularExpressions.Regex CSVParser = new System.Text.RegularExpressions.Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
String[] split = CSVParser.Split(line);
       ch.col1 = split[0].Replace("\"", "");
       ch.col2 = split[1].Replace("\"", "");
       return ch;
}).ToList<Items>(); 

// CSV files having multiple rows based on col1, so grouping them by col1 data
var group = (from d in items_MasterData
             select new Items
             {
                 col1 = d.col1,
                 col2 = d.col2
             }).GroupBy(n => new { n.col1 })
               .Select(g => g.FirstOrDefault());

//int countCol1Data = items_MasterData.Select(x => x.col1).Distinct().Count();
           
List<Items> col1Data = items_MasterData.GroupBy(n => new { n.col1 }).Select(g => g.FirstOrDefault()).ToList();


Thursday, November 21, 2019

C#: Consuming an API | HttpWebRequest/Response | Post Method

Code Snippet:
ServicePointManager.Expect100Continue = true;            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback = delegate (object s,
                System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                System.Security.Cryptography.X509Certificates.X509Chain chain,
                System.Net.Security.SslPolicyErrors sslPolicyErrors)
            {
                return true;
            };


 var req = (HttpWebRequest)WebRequest.Create(@"https://example.com");
 req.Method = "POST";
 req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("userid:password"));
            //req.Credentials = new NetworkCredential("username", "password");
req.ContentType = "application/json";

var reqbody = new Requestheaderdata()
{
    timeoutseconds = "300",
    userrole = "sample"
};
var requestData = JsonConvert.SerializeObject(reqbody);
           
   

 var bytes = Encoding.ASCII.GetBytes(requestData);
 req.ContentLength = bytes.Length;
 using (var outputStream = req.GetRequestStream())
 {
     outputStream.Write(bytes, 0, bytes.Length);
 }

 HttpWebResponse resp = req.GetResponse() as HttpWebResponse;


Monday, January 28, 2019

Encapsulation in Object oriented programming

Encapsulation is used to hide the code and data in a single unit to protect the data from the outside the world. Class is the best example of encapsulation.

Encapsulation provides a way to protect the data from accidental corruption.


Friday, October 26, 2018

Difference between the 'var' and 'dynamic'

var           -    The type of the variable declared is decided at compile time
dynamic   -    The Type of the variable declared is decided at run-time. 
  • variable declared using var should be initialized at time of declaration. However variables declared using keyword dynamic don't have to initialize at time of declaration.
  • The type of variable value assigned to var is decided at compile time and cannot be assigned with other types in the code later, having though gives compile. However variables declared using dynamic, compiler will not check for the type errors at the time of compilation. So variable can be assigned with values of any type through the code consecutively.
  • variable declared using var gives the intelliSense. However the variable using dynamic doesn't show the intelliSense because the type is decided at run-time, compiler never knows its type during compilation time.
Code Snippet:

            var str = "Hello Developer.!"; // str is decided as type string at compile time.
            str = 1;
            // compiler error - Cannot implicitly convert type 'int' to 'string'
           

            dynamic dn = 1001;
            dn = "text"; 

            // NO error is thrown by compiler, though variable is assigned to string. compiler will create the type of dn as integer and then it recreates the type as string when the string is assigned to it.


Now,
dynamic dn;
dn = "text";
var vr = dn;

vr = 1001;

// vr is assigned with dynamic dn - So vr type is decided at run-time.

Friday, September 21, 2018

Check the current Identity and Reset the Identity

Code Snippet:



// Check the current identity of the table
SELECT IDENT_CURRENT('tablename') 


 //Reset the identity to next incremental value
DBCC CHECKIDENT ('tablename', RESEED, 0)




When RESEED is used then the numbervalue in third argument of the CHECKIDENT is set as current identity for the table. Here in this case RESEED to 0 means 



Calling a WebMethod from User control in ASP.NET

This is a framework limitation, we cannot call the webmethod in the code behind file of user control from ascx file.

However try calling the webmethod in aspx code behind file from the ascx file. This will work