Quantcast
Channel: Visual C# forum
Viewing all 31927 articles
Browse latest View live

C# Extract an exact value from a JSON file.

$
0
0

I am fairly new to all things C#.
Sorry for making a JSON post as there are many and no matter how many I read, I cannot find the answer I am looking for.
I am all over the place and read so many examples that do not work for me, I am now just confused where to begin.

I made something where I can iterate through the entire file but not just return a specific value.

I have a JSON file with thousands of entries. In my example I am only going to show 3 entries.

First - I want to extract and print only the values for the ip that = 8.8.8.8. I will take those values and save them in a new file in a different format.

If I am unclear on what I am asking and need to add any more details, please ask. 

My file: file1.json

[
  {"ip": "1.1.1.1","latitude": -33.494,"longitude": 143.2104
  },
  {"ip": "2.2.2.2","latitude": 48.8582,"longitude": 2.3387
  },
  {"ip": "8.8.8.8","latitude": 37.751,"longitude": -97.822
  }
]

Thank you - Keith



Cannot assign to 'Write' because it is a 'method group'_?

$
0
0

Hi! I'm new with c# and i have a question. I want to create new jagged array when I scroll it,  But it says  "Cannot assign to 'Write' because it is a 'method group'" 

            

namespace ArrayandString{
    class initiali {
        static void Main() { 
        int[][] jagged = new int[3][];
            jagged[0] = new int[4];
            jagged[1] = new int[5];


            int i;
            // store values in first array
            for (i = 0; i < 4; i++) 
                jagged[0][i] = i;

            // store values in second array
            for (i = 0; i < 5; i++)
                jagged[1][i] = i;

            // display values in first array
            for (i = 0; i < 4; i++) 
                Console.Write = (jagged[0][i] + " ");
                Console.WriteLine = (" ");

            //display values in second array
            for (i=0; i<5; i++)
                Console.Write = (jagged[1][i] + " ");
                Console.WriteLine = (" ");

        }
    }
}

I am truly grateful for all your help

Sorry , my poor English

What is the benefit of simplified object initialization?

$
0
0

I have code like this

var form = new GetDate();
form.Text = "Assigned";
form.PreviousDate = txtEntered.Tag as DateTime?;
form.txtDate.Text = txtAssigned.Text == string.Empty ? DateTime.Now.ToString("MM/dd hh:mm") : txtAssigned.Text;
form.ShowDialog();

Visual Studio would rather this code be like this

var form = new GetDate
{
	Text = "Assigned",
	PreviousDate = txtEntered.Tag as DateTime?
};
form.txtDate.Text = txtAssigned.Text == string.Empty ? DateTime.Now.ToString("MM/dd hh:mm") : txtAssigned.Text;
form.ShowDialog();
Ok, but why? The VS suggestion seems less readable to me. Is there a compiled benefit?

maintain original source formatting while pasting with Range.PasteSpecial

$
0
0

This question is related to Office Interop.

I'm trying to paste RTF content in word document using method Range.PasteSpecial method. I have following line of code :

Clipboard.SetData(System.Windows.DataFormats.Rtf, text);
initialRange.PasteSpecial(DataType: Microsoft.Office.Interop.Word.WdPasteDataType.wdPasteRTF);

but problem with PasteSpecial is, it doesn't maintain the original formatting from the RTF source e.g. in my RTF source font of the text is Times New Roman but in resulting document after paste, font of the text is Calibri (which is the default font of word template file).

I'm aware about the method Range.PasteAndFormat method which accepts formatting option but I'm not able to use that method due to some reason. 

Anyway to maintain original source formatting using PasteSpecial method?


Krunal C

Read a string from a pascal dll

$
0
0

Hi,

Ik have a pascal dll which has a function that returns a Widestring.

Now i want to use the dll in C# like this:

[DllImport(@"Test.dll", CallingConvention = CallingConvention.StdCall)] public static extern string GetOne();

 private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                 textBox1.Text = GetOne();
            }
            catch (Exception ex)
            {
                string tmp = "Just to read the exception when debugging";
            }
        }

I get this warning: Test.exe has triggered a breakpoint.

How to imprt a string from a Pascal DLL?

I want to generate stored procedure from edmx to sql

$
0
0
I want to generate stored procedure from Edmx to the database but I don't  have  THE database I Have   the entity framework

c# knowing where/how to put a foreach loop while writing kml files

$
0
0

Hi -

I figured out how to write a KML file using static information. I can use variables if I only am writing one location in my KML file.

Not sure how best to describe this:

I need help of taking the following code and knowing where to put a foreach loop to iterate through the information from a file. I keep getting errors because of the placement of ")"'. 

Here is my code using static values. I want to pull from a file with a foreach loop. My trouble is the placement of ")" in and outside of the foreach loop. 

using System;
using System.IO;
using System.Xml.Linq;

namespace XML_Test_03
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("\n");

            XNamespace n = "http://earth.google.com/kml/2.2";
            XElement kmldoc = new XElement(n + "kml", new XElement(n + "Document",
                new XElement(n + "name", "HeatMap01"),

                new XElement(n + "Placemark", new XAttribute("id", "1"),
                new XElement(n + "name", "Baltimore, MD"),
                new XElement(n + "description", "Desciption of Baltimore"),
                new XElement(n + "Point",
                new XElement(n + "coordinates", "-76.61218,39.29038,0"))),

                new XElement(n + "Placemark", new XAttribute("id", "2"),
                new XElement(n + "name", "Washington DC"),
                new XElement(n + "description", "Desciption of Washington DC"),
                new XElement(n + "Point",
                new XElement(n + "coordinates", "-77.03687,38.90719,0"))),

                new XElement(n + "Placemark", new XAttribute("id", "3"),
                new XElement(n + "name", "Annapolis, MD"),
                new XElement(n + "description", "Desciption of Annapolis, MD"),
                new XElement(n + "Point",
                new XElement(n + "coordinates", "-76.4921829,38.9784453,0"))),

                new XElement(n + "Placemark", new XAttribute("id", "3"),
                new XElement(n + "name", "Mt. Airy, MD"),
                new XElement(n + "description", "Desciption of Mt. Airy, MD"),
                new XElement(n + "Point",
                new XElement(n + "coordinates", "-77.154704,39.3762145,0")))));

            Console.WriteLine("\n" + kmldoc);

            File.WriteAllText(@"c:\tmp\test-kml03.kml", kmldoc.ToString());

        }
    }
}

Thank you -
Keith

IComparer vs Generic IComparer

$
0
0

Hello,

Which one is better at performance?

Thanks

   class SortYearAscending : IComparer
    {
        public int Compare(object x, object y)
        {
            Person P1 = (Person)x;
            Person P2 = (Person)y;

            if (P1.Year > P1.Year)
                return 1;
            else if (P1.Year < P1.Year)
                return -1;
            else return 0; 
        }
    }

And

    class SortYearAscending : IComparer<Person>
    {
        public int Compare(Person P1,Person P2)
        {
            if (P1.Year > P1.Year)
                return 1;
            else if (P1.Year < P1.Year)
                return -1;
            else return 0; 
        }
    }


C# HttpWebRequest Through Proxy

$
0
0

hi guys

I want to use a proxy list in http requests. But when multiple HTTP requests are executed, the device's IP is blocked by the firewall server

Most of the available sources suggest the following method but the output is incorrect...

HttpWebRequest request =WebRequest.Create(url)asHttpWebRequest;
request.Proxy=newWebProxy("1.2.3.4:8080");//Proxy AdreessWebResponse myResponse = request.GetResponse();

Is it possible to force the compilation of DynamicMethod

$
0
0

I'm working on a Json serialization solution. I found out that the serialization based on emitting was much faster than direct operations on Reflection api after the emitted code had already been run once(each time with different data). Obviously the problem is JIT. So I wonder wether there is a way to force the compilation of DynamicMethod. The PreJIT feature,provided by Runtime.CompilerServices.RuntimeHelpers.PrepareMethod, simply doesn‘t work because we have no access to RuntimeMethodHandle of DynamicMethod. So is there other way to achieve this goal?

Thanks in advance.



Screen turns black before running screen saver code

$
0
0

Hello, I want to create a screen saver which will run only during night (from 20:00 to 06:00). So my code looks like this:

  1. Check time and if it is a day, exit.
  2. Run the Screen Saver Form

During the night everything is ok, but during the day, after specific time of inactivity, the screen turns black, then it runs the condition, the result is exiting the screen saver and then it show the desktop again.

My question is, why the screen turns black before running the screensaver? In the app of the screensaver there is nothing which should show black screen.

Insert DataTable To SQL Server Table

$
0
0
Hi - what is the way to push data from a DataTable to a SQL Server Table?

Http Reuse of connections

$
0
0

I look for a way to reuse connection and work in async at the same time.

first I loop over the data I get from the db : 

foreach (SmsMessage message in lSmsMessage)
                {
                    HttpManager httpManager = new HttpManager();
                    inputTaskList.Add(httpManager.SendData(strURL, message, Encoding.Default,xml);
                }

var results = await Task.WhenAll(inputTaskList);

and the HttpManager class :

public class HttpManager
    {
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        private readonly static string reservedCharacters = "!*'();:@&=+$,/?%#[]";
        public async Task<bool> SendData(string url, Message message, Encoding encodingPage,string baseXml)
        {
            string xml = BuildXml(message, baseXml);
            bool isSuccess = true;
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.ConnectionClose = false;//keeyp-alive
                string resultContent = string.Empty;

                client.BaseAddress = new Uri(url);
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("XML", xml)
                });
                try
                {
                    HttpResponseMessage result = await client.PostAsync("", content);
                    if (result.StatusCode == HttpStatusCode.OK)
                    {
                        resultContent = await result.Content.ReadAsStringAsync();
                        if(resultContent.IndexOf(">True<")>0)
                        {
                        }
                        else
                        {
                            isSuccess = false;
                            logger.Error("Failes to send1,reason={0}", resultContent);
                        }

                    }
                    else
                    {
                        isSuccess = false;
                        logger.Error("Failes to send2 CampaignId={3}");
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("Failes to send3()::failed sending Err={0}",  ex.Message);
                }

            }

            return isSuccess;
        }

        

        private static string ReplaceSpeicalChars(string txt)
        {
            txt=txt.Replace("&", "&amp;");
            return txt;
        }
    }

what is the corret wa to resuse the connections?


How to unzip a file in memory using an Azure CloudBlob

$
0
0
Azure doesn't allow me to unzip a file directly in a container.  I downloaded a zip file and now need to expand the file in the zip file.  What I get is a 0 byte file.  I can download the zip to my local computer and see the embedded csv, so the zip file isn't corrupt.  I get no errors, just a zero byte output file.  What am I doing wrong? I've tried all of these options unsuccessfully:

    using (MemoryStream ms = new MemoryStream())
    {
    await zipOutputBlob.DownloadToStreamAsync(ms);
    using (var zipStream = new GZipStream(ms, CompressionMode.Decompress))
    {
    CloudBlockBlob unzippedBlob = container.GetBlockBlobReference(String.Format("{0:yyyy-MM-dd}", lastWriteTime) + " " + Path.GetFileNameWithoutExtension(fileName) +  ".csv");
    unzippedBlob.Properties.ContentType = "text/csv";
    using (Stream outputFileStream = await unzippedBlob.OpenWriteAsync())
    {
    await zipStream.CopyToAsync(outputFileStream);
    outputFileStream.Flush();
    }
    }
    }

2nd try:

using (MemoryStream ms = new MemoryStream())
{
await zipOutputBlob.DownloadToStreamAsync(ms);
using (var zipStream = new GZipStream(ms, CompressionMode.Decompress))
{
CloudBlockBlob unzippedBlob = container.GetBlockBlobReference(String.Format("{0:yyyy-MM-dd}", lastWriteTime) + " " + Path.GetFileNameWithoutExtension(fileName) + ".csv");
unzippedBlob.Properties.ContentType = "text/csv";
await unzippedBlob.UploadFromStreamAsync(zipStream);
}
}

3rd

    using (MemoryStream ms = new MemoryStream())
    {
        await zipOutputBlob.DownloadToStreamAsync(ms);
        using (var zipStream = new GZipStream(ms, CompressionMode.Decompress))
        {
            CloudBlockBlob unzippedBlob = container.GetBlockBlobReference(String.Format("{0:yyyy-MM-dd}", lastWriteTime) + " " + Path.GetFileNameWithoutExtension(fileName) + ".csv");
            unzippedBlob.Properties.ContentType = "text/csv";
            using (Stream outputFileStream = await unzippedBlob.OpenWriteAsync())
            {
                await zipStream.CopyToAsync(outputFileStream);
                outputFileStream.Flush();
            }
        }
    }

4th    

    using (MemoryStream ms = new MemoryStream())
    {
        await zipOutputBlob.DownloadToStreamAsync(ms);
        using (DeflateStream decompressionStream = new DeflateStream(ms, CompressionMode.Decompress))
        {
            CloudBlockBlob unzippedBlob = container.GetBlockBlobReference(String.Format("{0:yyyy-MM-dd}", lastWriteTime) + " " + Path.GetFileNameWithoutExtension(fileName) + ".csv");
            unzippedBlob.Properties.ContentType = "text/csv";
            using (Stream outputFileStream = await unzippedBlob.OpenWriteAsync())
            {
                await decompressionStream.CopyToAsync(outputFileStream);
                outputFileStream.Flush();
            }
        }
    }
    
5th

    using (var inputStream = new MemoryStream())
    {
        await zipOutputBlob.DownloadToStreamAsync(inputStream);
        inputStream.Seek(0, SeekOrigin.Begin);
    
        using (var gzStream = new GZipStream(inputStream, CompressionMode.Decompress))
        {
            using (var outputStream = new MemoryStream())
            {
                gzStream.CopyTo(outputStream);
                byte[] outputBytes = outputStream.ToArray(); // No data. Sad panda. :'(
                string output = Encoding.ASCII.GetString(outputBytes);
                CloudBlockBlob unzippedBlob = container.GetBlockBlobReference(String.Format("{0:yyyy-MM-dd}", lastWriteTime) + " " + Path.GetFileNameWithoutExtension(fileName) + ".csv");
                unzippedBlob.Properties.ContentType = "text/csv";
                await unzippedBlob.UploadTextAsync(output);
            }
        }
    }

6th
    
    using (var ms = new MemoryStream())
    {
        await zipOutputBlob.DownloadToStreamAsync(ms);
        ms.Seek(0, SeekOrigin.Begin);
    
        using (DeflateStream decompressionStream = new DeflateStream(ms, CompressionMode.Decompress))
        {
            using (var outputStream = new MemoryStream())
            {
                decompressionStream.CopyTo(outputStream);
                byte[] outputBytes = outputStream.ToArray(); // No data. Sad panda. :'(
                string output = Encoding.ASCII.GetString(outputBytes);
                CloudBlockBlob unzippedBlob = container.GetBlockBlobReference(String.Format("{0:yyyy-MM-dd}", lastWriteTime) + " " + Path.GetFileNameWithoutExtension(fileName) + ".csv");
                unzippedBlob.Properties.ContentType = "text/csv";
                await unzippedBlob.UploadTextAsync(output);
            }
        }
    }

Option 5 and 6 fail with this error message on the CopyTo method:
 > System.Private.CoreLib: Exception while executing function: DefinitiveHealthCare. System.IO.Compression: The archive entry was compressed using an unsupported compression method.

How is this done?

API: Send datatable as parameter to stored procedure

$
0
0
I have an idea after watching a video tut on Sending datatable as parameter to stored proc and need feedback. I have an API and I want to store update data sent to my API for a set period of time. Every 5 mins for example, I want to call my database and perform the update passing the data table as a parm to the stored proc. Basically one giant update every 5 mins as apposed to making literally thousands of to my database over a 5 min period of time. Is this possible? Can I use timers in API's? I've never stored data in an API is that even possible? 

How can you compare 2 text files and only populate list key value pair with only the matching keys and values

$
0
0

ok i have 2 text files and they are diffent formats one is all on one line and one is in brakets examples below 

file 1 << the one that is the template one i want to match the other 2 

template

the file i want to compare againt ( so check the file above for all text to the left side if there is a match in the file below add the key and value to list key value pair ) 

file 2 

File to compare

so in the program i can add the value of the pair to template above im going to add to my program so as example 

i know both file contain DisplayName blahblah so when it finds that those 2 files share the name be something like this 

"displayName" "Nrg" 

say i name the list key value pair 

elfenlist so would want something like this 

displayName = elfenlied[displayName];

but not sure how to check files and get all occorences of the same names in both files

Not able to print data table value in particular excel column using C#.NET

$
0
0

I am struggling last few days to print data table value in particular excel column.

I have the master table with data.

When i print master table data to excel, there is a condition to swap the column based on the reference table data
and print.

step1 
-----
Read the master table. screen shot below

Master Table


step2
-----
While printing the data into excel, first refer the column as mentioned below and swap the column and then print

Reference Column


step3
-----
Final Output in the excel after swaping the columns.

Note : pls. note down the master table and output in excel, there will be swaping the columns.
since the column has been refrenced.

Output Template

My Source Code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office;

namespace WinForm
{
    public partial class Form1 : Form
    {
        public string country = string.Empty;
        public Excel.Application xlApp = null;
        public Excel.Workbook XLWB = null;
        public Excel.Worksheet wsht = null;
        int IdxCurr = 0;
        int IdxPrev = 0;
        string colLineNoToPrint;

        public Form1()
        {
            InitializeComponent();
          
        }

        private void button1_Click(object sender, EventArgs e)
        {
            country = comboBox1.SelectedItem.ToString();
            DataTable boundTable = new DataTable();
            DataTable dtRefColumn = RefColumn();
            if (!string.IsNullOrEmpty(country))
            {

                IEnumerable<DataRow> query = from customer in dtRefColumn.AsEnumerable()
                                where customer.Field<string>("Country_Name") == country
                                select customer;

                boundTable = query.CopyToDataTable<DataRow>();
            }
            else
            {

            }

            DataTable dtMaster = dtMasterData();

            //print data to output template according to reference column
            SaveToExcel(dtMaster, dtRefColumn, country);

         
        }

        public void SaveToExcel(DataTable dtMaster, DataTable dtReftable, string country)
        {
            xlApp = new Excel.Application();
            xlApp.Workbooks.Add(true);
            wsht = xlApp.Worksheets.Add();
            wsht.Name = "S2";

            if (dtMaster.Rows.Count > 0)
            {
                for (int i = 0; i < dtMaster.Rows.Count; i++)
                {

                         //************* Struggling to print rows from here ****************
                         DataView dv = new DataView(dtMaster);

                         DataTable dt = dv.ToTable(true, dtMaster.Columns[i].ToString());

                        //Get Column Name
                        string colname = dtMaster.Columns[i].ToString();
                        //Get Reference column 
                        string RefCol = (dtReftable.AsEnumerable().Where(p => p.Field<string>("Country_Name") == country && p.Field<string>("Column_Name") == colname).Select(p => p.Field<string>("Excel_column"))).FirstOrDefault();
                        int TotRows = dtMaster.Rows.Count;
                        TotRows = 12 + TotRows;

                       
                       //To Print : Excel rows Should start to print from Rows 10
                        wsht.Cells[i][10] = dt.Rows[i].ToString();
                       //************* Struggling to print rows from here ****************
                  
                }
            }
            xlApp.Visible = true;
            xlApp.ActiveWorkbook.SaveAs(@"C:\Users\CompUMZ1A\Desktop\test.xlsx");
            xlApp.Quit();
        }

        public static DataTable dtMasterData()
        {

                DataTable tblData = new DataTable();
                tblData.Columns.Add("Prod_ID", typeof(string));
                tblData.Columns.Add("Prod_Name", typeof(string));
                tblData.Columns.Add("Prod_Quantity", typeof(string));
                tblData.Columns.Add("Prod_Expiry", typeof(string));
                tblData.Columns.Add("Prod_Manf_Date", typeof(string));
                tblData.Columns.Add("Prod_Region", typeof(string));
                tblData.Columns.Add("Prod_Head", typeof(string));
                tblData.Rows.Add("2020-1A", "Horlicks", "5000", "10-Jun-20", "05-Jan-20", "NewYork", "Sharuk");
                tblData.Rows.Add("2020-1B", "VIVA", "2000", "10-Jun-20", "05-Jan-20", "California", "Amit");
                tblData.Rows.Add("2020-1C", "Complan", "30000", "10-Jun-20", "05-Jan-20", "Mexico", "John");
                tblData.Rows.Add("2020-1D", "Bournvita", "10000", "10-Jun-20", "05-Jan-20", "NewJersy", "Rauf");

                return tblData;
          
        }


        public static DataTable RefColumn()
        {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("Column_ID", typeof(string));
            dataTable.Columns.Add("Column_Name", typeof(string));
            dataTable.Columns.Add("Excel_column", typeof(string));
            dataTable.Columns.Add("Country_Name", typeof(string));
            dataTable.Columns.Add("Status", typeof(string));
            dataTable.Rows.Add("Prod_ID", "Prod.No", "H", "USA", "Active");
            dataTable.Rows.Add("Prod_Name", "Prod.Name", "A", "USA", "Active");
            dataTable.Rows.Add("Prod_Quantity", "Quantity", "C", "USA", "Active");
            dataTable.Rows.Add("Prod_Expiry", "Expiry Date", "D", "USA", "Active");
            dataTable.Rows.Add("Prod_Manf_Date", "Manufacturing Date", "E", "USA", "Active");
            dataTable.Rows.Add("Prod_Region", "Region", "B", "USA", "Active");
            dataTable.Rows.Add("Prod_Head", "Head of Region", "G", "USA", "Active");
            dataTable.Rows.Add("Prod_ID", "Prod. No", "B", "UK", "Active");
            dataTable.Rows.Add("Prod_Name", "Prod. Name", "A", "UK", "Active");
            dataTable.Rows.Add("Prod_Quantity", "Quantity", "X", "UK", "Active");
            dataTable.Rows.Add("Prod_Expiry", "Expiry Date", "M", "UK", "Active");
            dataTable.Rows.Add("Prod_Manf_Date", "Manufacturing Date", "N", "UK", "Active");
            dataTable.Rows.Add("Prod_Region", "Region", "O", "UK", "Active");
            dataTable.Rows.Add("Prod_Head", "Head of Region", "K", "UK", "Active");
            dataTable.Rows.Add("Prod_ID", "Prod. No", "A", "INDIA", "Active");
            dataTable.Rows.Add("Prod_Name", "Prod. Name", "B", "INDIA", "Active");
            dataTable.Rows.Add("Prod_Quantity", "Quantity", "C", "INDIA", "Active");
            dataTable.Rows.Add("Prod_Expiry", "Expiry Date", "D", "INDIA", "Active");
            dataTable.Rows.Add("Prod_Manf_Date", "Manufacturing Date", "E", "INDIA", "Active");
            dataTable.Rows.Add("Prod_Region", "Region", "F", "INDIA", "Active");
            dataTable.Rows.Add("Prod_Head", "Head of Region", "F", "INDIA", "Active");

            return dataTable;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("USA");
            comboBox1.Items.Add("UK");
            comboBox1.Items.Add("INDIA");
        }
    }
}

pls. have a look inside the code, and let me know where we have to change the code to print appropriate columns in excel...

Waiting for favourable reply.

General Questions About C# High Performance

$
0
0
Hello,

When you make a performance you can use the syntax code Stopwatch() to make a measurement but I have some general question about it.

1.
Should you use the syntax code "Stopwatch stopwatch = new Stopwatch();" in production phase. I have heard that this syntax takes a lot performance.
Is there another approach to use it?

2.
Is there any other option / tool that is not to use "Stopwatch stopwatch = new Stopwatch();" in order to make a mesurement?

3.
Is there any other advice that I should be aware about high performance?


Thank you!

OU Under A Service Account in Active Directory Using C#

$
0
0

I want to create a OU under the Service Account ABC in Active Directory using C#, Please help


Improve DataTable filling perfomance

$
0
0

I have a list containing 21 YYYYMM (years and months) which I loop though a Parallel processing, executing a query and populating a DataTable which further will be written into a csv file as you can see bellow.

Just the "Load" method in DataTable is taking 30 minutes to be executed, thereof I was looking to some suggestions how could I improve it.

lstFilterValues.AsParallel().ForAll(filterValue =>
                {

                    using (SAConnection _conn = DB_Connection.Connect(_psfAcronym))
                    { 
                    
                        var queryWithFilter = mainQuery.Replace("@FILTER", filterValue.ToString());

                        IDataReader _dataReader = new SACommand(queryWithFilter, _conn).ExecuteReader();

                        var _dataTable = new DataTable();
                        _dataTable.Load(_dataReader);

                        List<T> lstTableRows = new List<T>(TransformToObject.DataTableToList<T>(_dataTable));

            using (var sw = new StreamWriter(filePath))
            using (var csv = new CsvWriter(sw))
            {
                csv.Configuration.Delimiter = UniversalVariables.csvDelimiter.ToString(); ;
                csv.Configuration.HasHeaderRecord = true;
                csv.Configuration.UseNewObjectForNullReferenceMembers = true;

                csv.WriteHeader<T>();
                csv.NextRecord();
                csv.WriteRecords(lstRecords);

                sw.Flush();
            }

                        SybaseIQ_Connection.Disconnect(_conn);

                    }

                });


Viewing all 31927 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>