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

C# how to use different timer with different intervals, but start and stop them at the same time

$
0
0

Hello:

I have to use 2 timers and start and stop them at the same time, having one timer with interval of 1 second, another timer with interval of 2 seconds.  The following is my C# (.NET Core) code:

using System;
using System.Threading;

namespace TimerTask2
{
    class Program
    {
        static void Main()
        {
            AutoResetEvent autoEvent1 = new AutoResetEvent(false);
            StatusChecker1 statusChecker1 = new StatusChecker1(10);
            TimerCallback timerDelegate1 =
                new TimerCallback(statusChecker1.CheckStatus);
            TimeSpan delayTime1 = new TimeSpan(0, 0, 1);
            TimeSpan intervalTime1 = new TimeSpan(0, 0, 0, 0, 1000);
            Console.WriteLine("{0} Creating timer1.\n",
                DateTime.Now.ToString("h:mm:ss.fff"));
            Timer stateTimer1 = new Timer(
                timerDelegate1, autoEvent1, delayTime1, intervalTime1);
            autoEvent1.WaitOne(10000, false);
            stateTimer1.Dispose();
            Console.WriteLine("\nDestroying stateTimer1.");

            AutoResetEvent autoEvent2 = new AutoResetEvent(false);
            StatusChecker2 statusChecker2 = new StatusChecker2(5);
            TimerCallback timerDelegate2 =
                new TimerCallback(statusChecker2.CheckStatus);
            TimeSpan delayTime2 = new TimeSpan(0, 0, 2);
            TimeSpan intervalTime2 = new TimeSpan(0, 0, 0, 0, 2000);
            Console.WriteLine("{0} Creating timer2.\n",
                DateTime.Now.ToString("h:mm:ss.fff"));
            Timer stateTimer2 = new Timer(
                timerDelegate2, autoEvent2, delayTime2, intervalTime2);
            autoEvent2.WaitOne(10000, false);
            stateTimer2.Dispose();
            Console.WriteLine("\nDestroying stateTimer2.");
        }
    }

        class StatusChecker1
        {
            int invokeCount, maxCount;

            public StatusChecker1(int count)
            {
                invokeCount = 0;
                maxCount = count;
            }

            public void CheckStatus(Object stateInfo)
            {
                AutoResetEvent autoEvent1 = (AutoResetEvent)stateInfo;
                Console.WriteLine("{0} Checking status {1,2}.",
                    DateTime.Now.ToString("h:mm:ss.fff"),
                    (++invokeCount).ToString());
                if (invokeCount == maxCount)
                {
                    invokeCount = 0;
                    autoEvent1.Set();
                }
            }
        }

        class StatusChecker2
    {
        int invokeCount, maxCount;

        public StatusChecker2(int count)
        {
            invokeCount = 0;
            maxCount = count;
        }

        public void CheckStatus(Object stateInfo)
        {
            AutoResetEvent autoEvent2 = (AutoResetEvent)stateInfo;
            Console.WriteLine("{0} Checking status {2,2}.",
                DateTime.Now.ToString("h:mm:ss.fff"),
                (++invokeCount).ToString());
            if (invokeCount == maxCount)
            {
                invokeCount = 0;
                autoEvent2.Set();
            }
        }
    }
}

My code can get compiled, but when run, it has the following error:

System.FormatException
  HResult=0x80131537
  Message=Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
  Source=System.Private.CoreLib
  StackTrace:
   at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
   at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
   at System.IO.TextWriter.WriteLine(String format, Object arg0, Object arg1)
   at System.Console.WriteLine(String format, Object arg0, Object arg1)
   at TimerTask2.StatusChecker2.CheckStatus(Object stateInfo) in C:\Test\Helper\TimerTask2\TimerTask2\Program.cs:line 77
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)

Besides, it seems the first timer runs, then the second timer runs.

I want the both to run at the same time, and stop at the same time.

Is there any way to do this?

Thanks,

PS: My IDE: Visual Studio 2019 (Version 16.1.5) on Windows 10 (Version 1903).


txtbox.DataBindings with foreign table's attribute

$
0
0

Sorry my question may be a bit hard to understand.

I have a listbox that displays Vacancy.Description

lstBoxVacancy.DataSource = DM.lookingGlassDS;                                               
lstBoxVacancy.DisplayMember = "Vacancy.Description";                                        
lstBoxVacancy.ValueMember = "Vacancy.Description"; 



When you click on one of the items in the listbox, the text boxes on the side correlate to the selected description row(Vacancy.Description).



txtVacancyID.DataBindings.Add("Text", DM.lookingGlassDS, "Vacancy.VacancyID");   

txtDescription.DataBindings.Add("Text", DM.lookingGlassDS, "Vacancy.Description"); 

txtStatus.DataBindings.Add("Text", DM.lookingGlassDS, "Vacancy.Status");  

txtSalary.DataBindings.Add("Text", DM.lookingGlassDS, "Vacancy.Salary"); 

txtVacancyEmployerID.DataBindings.Add("Text", DM.lookingGlassDS, "Vacancy.EmployerID");

txtVacancyEmployerName.DataBindings.Add("Text", DM.lookingGlassDS, "Employer.EmployerName");


However, for the EmployerName value, the "Employer Name:" textbox is not changing when you select a new item in the listbox. I think this is because EmployerName comes from the Employer table and not the Vacancy table like the rest of the DataBindings.

txtVacancyEmployerName.DataBindings.Add("Text", DM.lookingGlassDS, "Employer.EmployerName");

My question is how do I make it so that when I click on a listbox item (Vacancy.Description), the associated EmployerName(Employer.EmployerName) is displayed in the EmployerName textbox?

In my DataSet, it says the relation name is EMPLOYERVACANCY between the Employer and Vacancy table. Parent table: EMPLOYER. Child table: VACANCY Primary key: EmployerID, Forgein key:EmployerID

Thank you very much


how can I get the selectednode attribute into the list variable. Please help

$
0
0

Sorry for disturbing you all. This might be the last question from my side to read the xml file

I want to get the SQL ID name into the list string variable. The list string should be stored with SQLS1, SQLS2

My code

foreach (var child in subjectList)
                    {
                        if (child is XmlNode)
                        {
                            var element = (XmlNode)child;
                            if (element.HasChildNodes)
                            {
                                var attributes = element.Attributes;
                                xmlData.Tagid = element.Attributes["ID"].Value;
                                //xmlData = GetSQL(element);
                                foreach (var item in attributes)
                                {
                                    string id = element.Attributes["ID"].Value;
                                    xmlData.ListSql =
                                            element
                                            .SelectNodes("SQL/comment()")
                                            .Cast<XmlComment>()
                                            .Select(c => c.Value.Trim())
                                            .ToList();

                                    xmlData.EmailAddressList =
                                            element
                                            .SelectNodes("Address")
                                            .Cast<XmlNode>()
                                            .Select(c => c.InnerText.Trim())
                                            .ToList();
                                    xmlData.mailSubject =
                                             element
                                            .SelectNodes("MailSubject")
                                            .Cast<XmlNode>()
                                            .Select(c => c.InnerText).FirstOrDefault();
                                    xmlData.mailBody =
                                             element
                                            .SelectNodes("MailBody")
                                            .Cast<XmlNode>()
                                            .Select(c => c.InnerText).FirstOrDefault();
                                    xmlData.fileName =
                                             element
                                            .SelectNodes("FileName")
                                            .Cast<XmlNode>()
                                            .Select(c => c.InnerText).FirstOrDefault();List<string> sheetID =
                                           element
                                           .SelectNodes("SQL")
                                           .Cast<XmlNode>()
                                           .Select(c => c.Attributes("ID")) Here not working ?????
                                           .ToList();


                                    
Please help

                                }
                                _filename = CreateExcelFile(xmlData, _excelfolder,database);

                            }
                        }
                    }

XML

<?xml version="1.0" encoding="utf-8" ?><STATEMENT><CUSTOMER ID = "CUSTOMER1"><SQL ID="SQLS1"><!-- Select Rate From Product --></SQL><SQL ID="SQLS2"><!-- select Qty from Product --></SQL><Address>test1@gmail.com</Address><Address>test2@gmail.com</Address><Address></Address><MailSubject>Statement</MailSubject><MailBody>Please find statement</MailBody><FILENAME>Statement2</FILENAME></CUSTOMER><CUSTOMER ID = "CUSTOMER2"><SQL ID="SQLS"><!-- Select Code from Customer --></SQL><SQL ID="SQLS3"><!-- select name from supplier --></SQL><SQL ID="SQLS4"><!-- select qty from purchase--></SQL><EmailAddress>test3@gmail.com</Address><EmailAddress>test4@gmail.com</Address><MailSubject>statement</MailSubject><MailBody>Please find statement</MailBody><FILENAME>Statement2</FILENAME></CUSTOMER></STATEMENT>


polachan

How to pass windows credential to ASP.NET Core Web API controller

$
0
0

I developed the ASP.NET Core Web API using windows autherntication. The URL is http://abc.com:8080. 

I can login to this Web API via browser and get the data back within the company internal network. I enabled the windows autherntication in IIS site.

Now I want to call this Web API from another ASP.net web site such as SharePoint 2019 with the same domain name as the Web API URL. It's https://abc.com:443. I used the same windows credential login to the SharePoint.

I saw the error message that "The request needs credential / autherntication ...",  the api call is failure.

How to pass the windows credential to  the ASP.NET Core Web API?

Hoe to remove gray space from datagridview in c# windows form

$
0
0

hi, i'm trying to remove blank space from datagridview. the datagridview is bind with sqlite database.

after run the project

i use this code

private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                dataGridView1.MaximumSize = new Size(this.dataGridView1.Width, 0);
                dataGridView1.AutoSize = true;

                using (SQLiteConnection conn = new SQLiteConnection("Data Source=data.db"))
                {
                    string CommandText = "SELECT * FROM testing";
                    using (SQLiteDataAdapter sda = new SQLiteDataAdapter(CommandText, conn))
                    {
                        DataSet ds = new DataSet();
                        sda.Fill(ds);
                        dataGridView1.DataSource = ds.Tables[0].DefaultView;
                    }
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

how can i resolve this....

Difference between IIS Express VS and IIS LocalHost.

$
0
0
I had develop a web application use for SCADA project. There is a part that the app needs to send XML data to XML site for client's reference. When I do testing using IIS Express VS everything work fine, but problems come when I run with IIS LocalHost. It can't send XML data to XML site. Besides, both IIS integration with database work fine. What cause this happen?

Copy files from one folder to another folder using C# Windows Services

$
0
0

HI,

I want to create one winidows services using C#.

The Basic functionality should i want in the windows services is as follows.

1. Admin people will copy the files(xml files) into one specific folder.

2. windows Services has to keep pooling /watching the above file directory if any files were exists. if any files are exists, windows services will copy one by one file to another folder. After  copying one  file(xml file), windows services will create one text file and writes into the text  file as some text (eg: "copyed").

3. My application Server(BizTalk) will take the file and process to orchestration. after finishing orchestration, biztalk will modify the above text file data as 'processed'.

4. again windows services copy another file , if the text file data as 'processed'. and updates text file as 'copyed'

5. steps 2,3,4 keeps working until all the files are copied.

Pls help how to achieve the above processs using windows services(c#) and provide me some related link OR code to write in windows services appln.

Regards,

Syam M

Extract data from Repeating record

$
0
0

Hi All,

I want o extract data from repeating record present in xml and store that record in a file.

for example 

<root>
<Participants xmlns="">
<Gender>F</Gender>
<FirstName>A Giam</FirstName>
<MiddleName/>
<LastName>Lek</LastName>
</Participants>
<Participants xmlns="">
<Gender>F</Gender>
<FirstName>B Giam</FirstName>
<MiddleName/>
<LastName>Lek</LastName>
</Participants>
<Participants xmlns="">
<Gender>F</Gender>
<FirstName>C Giam</FirstName>
<MiddleName>Rock</MiddleName>
<LastName>Layer</LastName>
</Participants>
</root>

i want to store First name, and last name in a file. 

Kindly help !!


C# Programming

$
0
0

Create a program that will calculate employee’s monthly gross pay as follows:

Inputs:

  1. Name
  2. Annual Salary
  3. Monthly Sales
  4. Keeps asking for additional inputs and creating the outputs until an empty name is entered.

Outputs:

  1. Name
  2. Monthly Base Pay (Salary / 12)
  3. Commission calculated as follows:
    1. Subtract 10 * Monthly Base Pay from Monthly Sales giving Net Sales
    2. If the Net Sales is <= 0, then the Commission is 0
    3. Otherwise the First $10,000 in Net Sales is commissioned at 5%
    4. The next $15,000 in Net Sales is commissioned at 10%
    5. The next $25,000 in Net Sales is commissioned at 15%
    6. Any Net Sales over $50,000 is commissioned at 20%
  4. Gross Pay (Monthly Base Pay + Commission).
  5. If any of the inputs are unreasonable, tell user with a message and force reentry of the data (e.g. Negative Sales, Annual Salary > $120,000 or < $12,000, if not 0).

Additional Requirements:

  1. Create a class to contain the employee data.
    1. Need class attributes for: name, base pay, sales
    2. Create accessors and mutators for all the data above
    3. Create routine to return gross pay
    4. Create constructor(s)
  2. Create an array of that class.
  3. Create a menu system that allows:
    1. Employees to be added to the employee list
    2. Sales for month to be entered
    3. Report on pay created
    4. Exit the program
  4. You may use global variables for the item 2 array and the number elements in the array in use.
  5. Create static methods to:
    1. Handle menu
    2. Add new employees
    3. Enter sales for month
    4. Produce the pay report.

:Example input and Output (user input in Bold):

Enter employee's name (enter nothing to quit):Howard

Enter Annual Salary (0 for pure commission):30000

Enter Monthly Sales:40000

Howard     Base Salary=$2,500.00  Sales=$40,000.00  Commission=$1,000.00  Gross Pay= $3,500.00

Enter employee's name (enter nothing to quit):Tom

Enter Annual Salary (0 for pure commission):0

Enter Monthly Sales:40000

Tom        Base Salary=    $0.00  Sales=$40,000.00 Commission=$4,250.00  Gross Pay= $4,250.00

Enter employee's name (enter nothing to quit):Sally

Enter Annual Salary (0 for pure commission):0

Enter Monthly Sales:60000

Sally      Base Salary=    $0.00  Sales=$60,000.00 Commission=$7,750.00  Gross Pay= $7,750.00

Enter employee's name (enter nothing to quit):Joe

Enter Annual Salary (0 for pure commission):30000

Enter Monthly Sales:20000

Joe        Base Salary=$2,500.00  Sales=$20,000.00  Commission=    $0.00  Gross Pay= $2,500.00

Enter employee's name (enter nothing to quit):

How to use Multi-Core CPU to increase performance

$
0
0

Hello:

I have the following C# (.NET Core Version 2.2) project built by Visual Studio 2019 (Version 16.1.5) on Windows 10 (Version 1903)

using System;
using System.Threading.Tasks;

namespace MultiCorePerformance1
{
    class Program
    {
        static async Task DoProdJob(int prod_item1)
        {
            if (prod_item1 >= 1)
                Console.WriteLine("Save prod_item1 into [PROD_TABLE], Done @{0}", DateTime.Now.ToLocalTime());
            await Task.Delay(0);   
        }

        static async Task DoTotalJob(int total_item1)
        {
            if (total_item1 >= 2)
                Console.WriteLine("Save total_item1 into [TOTAL_TABLE], Done @{0}", DateTime.Now.ToLocalTime());
            await Task.Delay(0);
        }

        static async Task DoDifferJob(int diff_item1)
        {
            if (Math.Abs(diff_item1) >= 1)
                Console.WriteLine("Save diff_item1 into [DIFF_TABLE], Done @{0}", DateTime.Now.ToLocalTime());
            await Task.Delay(0);
        }

        static async void Main()
        {
            int item1 = 1, item2 = 2;
            int prod_items = item1 * item2;
            int total_items = item1 + item2;
            int differ_items = item1 - item2;
            await DoProdJob(prod_items);
            await DoTotalJob(total_items);
            await DoDifferJob(differ_items);
        }
    }
}

The code works OK, but the performance is not good. As this is the example code, the real code, each DoXXXJob contains using Puppeteer-Sharp to grab web page information and upload HTTP post data by HttpClient.

For each of the operation, the speed seems to be OK. For example, Puppeteer-Sharp grabbing web page information takes less than 10 milliseconds; HTTP post by HttpClient takes 300ms to 500ms.

I have total 8 of such DoXXXJob, each one will take place with different conditions, depend on the production, total and difference of 2 items: item1 and item2.

The biggest issue now is the performance is not good.

For example, the average time I see the output from Done @{0}", DateTime.Now.ToLocalTime());

Is about 1 minute, 2 minutes or even much longer after I got the both items.

As my PC comes with ADM CPU with 16 core.

I would like to know if I can use C# to fully utilize my multi-core CPU to boost the performance. I think if the output from Done @{0}", DateTime.Now.ToLocalTime()) is mostly from 10 to 15 seconds after I get the both items value, then the performance is good enough.

Please advice, which direction I should go. Better to provide either document link or some sample codes.

Thanks,

C# Cast derived class type to this of parent class using Type

$
0
0

Hello all!

I'm trying to use bit of my code like this:

class Parent
{
public Parent (Type child)
{
ChildA_or_B_Type foo = (child)this; // an error occured here
}
}

class ChildA : Parent
{
public ChildA () : base (this.GetType())
{

}
}

class ChildB : Parent
{
public ChildB () : base (this.GetType())
{

}
}

How to implement this convertation properly? I haven't found any solution.

Thank you.

How to merge lists in one big list?

$
0
0

I am trying  to merge many lists into one but without success. 

Here's what i have tried, anyone can tell me what's wrong.

List<double> tlist = new List<double>() {alist[a]};
List<double> ttlist = new List<double>() {zlist[z]};
          
          var list = tlist.Concat(ttlist).ToList();
          List<double> ulist = tlist.Union(ttlist).ToList();
          
          Print(ulist);

I tried with concat and union but i always get an error message:

System.Collections.Generic.List`1[System.Double]

I have to mention that those lists are from another lists like:

List<double> alist = new List<double>() {xlist[y]};
        
          for(int a = 0; a < alist.Count; a++)
            {
         alist[a] = (alist[a] + counter) / (someOtherInt - counter);
thank you

C# Programming Loops

$
0
0

Write an application that can be used to determine if three line segments can form a triangle. Prompt the user for the length of three line segments as integers. If non-numeric characters are entered, re-prompt the user for new values. If the three lines could form a triangle, print the integers and a message indicating that they form a triangle. Use a state-controlled loop to allow users to enter as many different combinations as they want.

A property that applies to triangles:
 *   The sum of the lengths of any two sides of a triangle is greater than the length of the third side.
 *   If you take the three sides of a triangle and add them in pairs, 
 *   the sum should be greater than the third side. i.e. 3-4-5  or  5-8-12
 *
 *  If that is not true, then it is not possible to construct a triangle with the given side lengths.



dictionary key value issue

$
0
0

ok so i have made a program that i am genrating a a dict to key value pairs and in this key value pairs they are enclosed in "" 

so i used the escape \ but when i adds the key value pair it adds it in like this

this is the code i have currently 

smgwep.Add("\"activate_mode\"", "\"hold\"");
            smgwep.Add("\"activate_with_primed_delay\"", "\"0\"");
            smgwep.Add("\"activatesSlam\"", "\"0\"");
            smgwep.Add("\"activatesSlamAsMelee\"", "\"0\"");
            smgwep.Add("\"activatesSlamAsPowerMelee\"", "\"0\"");
            smgwep.Add("\"activatesSlamAsPowerMeleeLeft\"", "\"0\"");
            smgwep.Add("\"acv_acog\"", "\"\"");
            smgwep.Add("\"acv_damage\"", "\"\"");
            smgwep.Add("\"acv_dualclip\"", "\"\"");
            smgwep.Add("\"acv_dualoptic\"", "\"\"");
            smgwep.Add("\"acv_dw\"", "\"\"");
            smgwep.Add("\"acv_dynzoom\"", "\"\"");
            smgwep.Add("\"acv_extbarrel\"", "\"\"");
            smgwep.Add("\"acv_extclip\"", "\"\"");
            smgwep.Add("\"acv_fastads\"", "\"\"");
            smgwep.Add("\"acv_fastreload\"", "\"\"");
            smgwep.Add("\"acv_fmj\"", "\"\"");
            smgwep.Add("\"acv_gl\"", "\"\"");
            smgwep.Add("\"acv_gmod0\"", "\"\"");
            smgwep.Add("\"acv_gmod1\"", "\"\"");
            smgwep.Add("\"acv_gmod2\"", "\"\"");
            smgwep.Add("\"acv_gmod3\"", "\"\"");
            smgwep.Add("\"acv_gmod4\"", "\"\"");
            smgwep.Add("\"acv_gmod5\"", "\"\"");
            smgwep.Add("\"acv_gmod6\"", "\"\"");
            smgwep.Add("\"acv_gmod7\"", "\"\"");
            smgwep.Add("\"acv_grip\"", "\"\"");
            smgwep.Add("\"acv_holo\"", "\"\"");
            smgwep.Add("\"acv_ir\"", "\"\"");
            smgwep.Add("\"acv_is\"", "\"\"");
            smgwep.Add("\"acv_mk\"", "\"\"");
            smgwep.Add("\"acv_mms\"", "\"\"");
            smgwep.Add("\"acv_none\"", "\"\"");

it saves out the the file ok puts in the quotes and format and all but the issue is the key names have the 

"\"activate_mode\"" "\"hold\""

and i wanted to know is there a way to remove the "\" form the key name so i can search smgwep["activate_mode"]

and on the save out it still save it within the quotes 

the save out function 

        public void saveout()
        {
            smgwep_class();
            using (StreamWriter writer = new StreamWriter(@"C:\Users\elfenliedtopfan5\Desktop\pdw.gdt"))
            {
                writer.Write("{" + Environment.NewLine);
                writer.WriteLine(    smgwep["displayName"] + "(\"bulletweapon.gdf\")"); //    "\"pdw57\"(\"bulletweapon.gdf\")"
                writer.WriteLine(	"}"+ Environment.NewLine);

               foreach (var entry in smgwep)
               writer.WriteLine("		{0} {1}", entry.Key, entry.Value);
            }
        }

thats how i want it to be but currently it tells me displayName does not exsist in dict witch is because it has all the "/ ect in frount of it 

any help would be much appeicated 

elfenliedtopfan5 


LINQ JOIN: Getting out of memory exception

$
0
0

see the code below

var QCViewAllHistValue1 = (from frmlst in cfList
   join viewalllst in QCViewAllBrokerList1
   on new
   {
       val = String.IsNullOrEmpty(frmlst.Section) ? "" : frmlst.Section.Trim().ToUpper(),
       val1 = String.IsNullOrEmpty(frmlst.xFundCode) ? "" : frmlst.xFundCode.Trim().ToUpper(),
       val2 = String.IsNullOrEmpty(frmlst.Period) ? "" : frmlst.Period.Replace("A", "").Replace("E", "").Trim().ToUpper(),
       val3 = String.IsNullOrEmpty(frmlst.Broker) ? "" : frmlst.Broker.Trim().ToUpper()
   }
   equals new
   {
       val = String.IsNullOrEmpty(viewalllst.ViewAllSection) ? "" : viewalllst.ViewAllSection.Trim().ToUpper(),
       val1 = String.IsNullOrEmpty(viewalllst.xFundCode) ? "" : viewalllst.xFundCode.Trim().ToUpper(),
       val2 = String.IsNullOrEmpty(viewalllst.ViewAllPeriod) ? "" : viewalllst.ViewAllPeriod.Replace("A", "").Replace("E", "").Trim().ToUpper(),
       val3 = String.IsNullOrEmpty(viewalllst.ViewAllBroker) ? "" : viewalllst.ViewAllBroker.Trim().ToUpper()
   }

   select new QCHelper()
   {
       Value = viewalllst == null ? string.Empty : (viewalllst.Value == null ? string.Empty : viewalllst.Value),
   }).ToList<QCHelper>();

cfList & QCViewAllBrokerList1 these are two List<T> type. i am joining these two list and gettingout of memory exception

these two list has more than 8,00.000 records may be this huge records causing this issue. my pc is 64 bit and 8GB RAM. i have windows 7 OS installed.

i follow these two links but there suggestion does not work for me.

https://stackoverflow.com/a/17322112/10839668

https://stackoverflow.com/a/53424048/10839668

please guide me how could i get rid of out of memory exception. thanks


Outlook Contact Item - Show Image in notes section using C#

$
0
0

Hi, 

I am currently using the   Microsoft.Office.Interop.Outlook

to generate the Outlook Contact through C# program.

now I wanted to show the image (i.e show the actual image in the notes section)

I am trying to achieve it but somehow I am only able to attach it

Please refer to attached screenshot

aNeed actual output like this -

Sample Code I am using

  OutLook._Application outlookObj = CheckForOutlookInstance();
                var fldContacts =
                    (OutLook.MAPIFolder)outlookObj.Session.GetDefaultFolder(OutLook.OlDefaultFolders.olFolderContacts);
                var newContact = (OutLook.ContactItem)fldContacts.Items.Add(OutLook.OlItemType.olContactItem);
  newContact.FirstName = "";
                newContact.LastName = "";
                newContact.Body = "test photo";
newContact.Attachments.Add(contactphotoPath);

  private OutLook._Application CheckForOutlookInstance()
        {
            var processes = Process.GetProcessesByName("OUTLOOK");

            var collCount = processes.Length;

            if (collCount != 0)
            {
                _outlookObj = (OutLook._Application) Marshal.GetActiveObject("Outlook.Application");
                return _outlookObj;
            }

            _outlookObj= new OutLook.Application();
            return _outlookObj;

        }


How to write code loop through account no on grid and add spaces to left and cut spaces on right but must all length be 15

$
0
0

I work on windows from app csharp visual studio 2015

I have windows form have datagridview name Grid1 

this grid have 5 rows and column name Account No

what i need is to loop through five rows and add spaces from left and remove spaces from right 

and in same time it must be have length 15 .

suppose i write account no  123321 what i need to do is loop through 5 records

then loop through column account no then make following

15 - length of account(123321)= 9

then add 9 spaces to left of number and not add any spaces to right 

meaning add 9 times ""

and in same time if number have right space remove it and add it to left of number 

but must length of number as 6 + spaces = 15

Example

'         123321'
'        476890 '

first one as 123321 is correct result

second one as 576890 is wrong because it have right space 

all number with spaces must be 15

so please how to do that 


How does this data assignment work?

$
0
0

This is standard code to add default values when adding a new row to a binding source. In the code below, the new row will be created with a default date of now (assume this row has a field called "Date").

private void RequestsBindingSource_AddingNew(object sender, AddingNewEventArgs e)
{
   var bs = sender as BindingSource;
   var dv = bs.List as DataView;
   var drv = dv.AddNew();
   drv.Row.SetField<DateTime>("Date", DateTime.Now);
   e.NewObject = drv;
}

I understand these assignments are done by reference. That is, the variable bs does not contain a copy of the value in sender, as it would if we were assigning ints. It contains a "reference" (which I assume is the address of but could be more complex) so the variables bs and sender both "point" to the same BindingSource (which in this case is called RequestsBindingSource).

But if my understanding is correct, the how come the line var drv = dv.AddNew(); doesn't trigger the AddingNew event, leading to infinite recursion and a quick crash? After all, the List that dv refers to is the same list RequestsBindingSource uses.


i want to to get all employee name from a table in a string in SQL

$
0
0
i want to to get all employee name from a table in a string in SQL

Can we access a web api from java code

$
0
0
Can we use a web api from java code
Viewing all 31927 articles
Browse latest View live


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