Go Premium for a chance to win a PS4. Enter to Win

x

C#

92K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

Share tech news, updates, or what's on your mind.

Sign up to Post

Hi Experts,
I need help with the layout of an HTML page in my MVC.Net application with C#.Net code behind.

Please see the attached image and let me know how to write the HTML.  

HTML Layout
Thank You in advance,
mrotor
0
Vote for the Most Valuable Expert
LVL 7
Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Hi,

I am doing some calculation based on my excel input.

This Excel user can select from the particular path and then select the file.

But, now client wants, they don't want to select excel file from the path.

Instead of that, they will mention the file path in the INI file.

While loading the form, first it should read the INI File and then read and convert into datatable.

I am new to use INI File.

Can anyone suggest how to write code to read the file from INI and convert those file into datatable

See my current code below..

 private void btnbrowse_Click(object sender, EventArgs e)
  {
            this.openFileDialog1.Filter = "Excel file (*.xls;)|*.xlsx";
            this.openFileDialog1.Multiselect = true;
            this.openFileDialog1.Title = "Select Excel";
            DialogResult dr = this.openFileDialog1.ShowDialog();
            DataTable dataTable1 = new DataTable();
            
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                foreach (String file in openFileDialog1.FileNames)
                {
                    Excelname = file;
                    txtXLfile.Text = Excelname;
                }
            }
            dtproject = getXLDatatable(Excelname, dataTable1);

            DataRow dr1;

            dr1 = dtproject.NewRow();
            dr1.ItemArray = new object[] { 0, "Select Project" };
            dtproject.Rows.InsertAt(dr1, 0);
            cmbProject.ValueMember  = 

Open in new window

0
I'm trying to pass a user selected value from a datagridview to a databound combobox. The combobox is populated via datatable. When trying to select the sheet # from the datatable it is finding nothing. I viewed the datatable contents by populating a datagridview from it directly before the issue code. The datagridview displayed 2800+ records that include the sheet # being passed in the filter.

The below code shows where the datatable and combobox are initially populated. The second part of code shows where I'm trying to find the sheet # from the dgv in the datatable. That part is not working for me. What can I try?

From Form_Load
            //Populate Sheet combobox.
            sqlDDS = "SELECT convert(char(2),sht_yy_dt) + sht_pgm_cls + convert(char(4),sht_seq_nbr) + sht_usg_txt sheet, cst_mfg_ord_nbr FROM sheet WHERE loc_id = " + cboJitl.Text + " ORDER BY convert(char(2),sht_yy_dt) + sht_pgm_cls + convert(char(4),sht_seq_nbr) + sht_usg_txt desc";
            cmd.CommandText = sqlDDS;
            OdbcDataAdapter daSheet = new OdbcDataAdapter(cmd);
            daSheet.Fill(dtSheet);
            this.cboSheet.SelectedIndexChanged -= new EventHandler(cboSheet_SelectedIndexChanged);
            this.cboSheet.DataSource = dtSheet;
            this.cboSheet.DisplayMember = "sheet";
            this.cboSheet.SelectedIndexChanged += new EventHandler(cboSheet_SelectedIndexChanged);

            //Attain the order id from sheet table to use for retrieving section and 

Open in new window

0
I have an encrypted data file which stores credentials for an environment - these credentials are used as part of an automated scripted deployment solution. Basically a process runs a number of scripts/installers to configure a windows environment, if one of these scripts/applications needs a password a 'middle-man' application is called with an 'action' parameter which will then call the target application directly and pass in the decrypted username/password pairs.

The idea behind this is the 'middle-man' application will be the only tool capable of decrypting the password and will then be only to run a defined set of commands using these passwords. By defining the exact commands that can be run and passed a secure parameter I can ensure no passwords are logged and that the "middle-man" application cannot be used in an improper way...

Hopefully that makes sense... The question here is - is there a better way of doing this, it seems like a very over-engineered solution which requires rewrites of the "middle-man" application every time a new action is needed in the installation process which requires a password?

Any ideas appreciated.
0
Hi Team,

I have old version of application developed using MS Visual Studio 2.0 used below code for set security setting to access .asmx web service

using Microsoft.Web.Service3;
using Microsoft.Web.Service3.Security;
using Microsoft.Web.Service3.Secuirty.Tokens;

///initialise the username token for soap security header

private void setsecuritysetting(mywebservice mywebservice)
{
usernametoken usertoken = new usernametoken(this.mywebserviceusername, this.webserivcepassword, passwordoption.sendhashed)

soapContext requestContext = mywebservice.Requestsoapcontext;
requestContex.security.token.add(usertoken);

}

I have upgraded this application from VS 2.0 to VS 2015 (4.5.2) but above code is not working
0
Hi, I am working on a complicated team project where I am not able to debug the code.  I am working with VS 2015 in a TFS environment and XrmToolKit to check in and build the plugin in CRM.

When attempting to debug a plugin, I get the attached message:
A project with an Output Type of Class Library cannot be started directly.
I have reviewed this with other developers on the team and they have had differing answers.  I need a way to set a breakpoint and step through the code to see what is not correct (missing quoteid, no guid, etc).

The answer I received was: Create a new .cs file in the unit test project to test code you want to implement.

Below is the code I was given for this process.  Set a break point where you want to debug the logic. Use the Test Explorer and locate your new .cs file.

using FakeXrmEasy;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using PACCAR_CRM_Code.Library;
using PACCAR_CRM_Code.Library.Result;
using PACCAR_CRM_Code.Plugins;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Xml;
using Xunit;

namespace UnitTestProject
{
    public class Test
    {
        private static string OrgService = "http://spaceshuttle-test/LaunchTest";

        [Fact]
        public void Test_Debug()
        {
            var utilities = new Utilities();
            var ctx = new XrmFakedContext();
            var TracingService = new 

Open in new window

0
Hi,

currently i am using SQL Server table in one of my application.

But, my client asking me to change the table to excel file or ini file which is located in server path.

the reason is to change to excel or ini file is, my client doesn't have access to change the name of the value in table.

For example,

Table structure is below.

EmpNo      Sub1      Sub2      Sub3      Sub4
1      100      200      400      500
2      200      300      400      500
3      400      500      300      400
instead of the above table client's want to maintain in excel which need to be read from the folder.

see my sql code.

SqlCommand cmd = new SqlCommand(@"select Sub1,Sub2,Sub3 where Empno=@EmpNo", sqlcon);
                    cmd.Parameters.Add("@EmpNo", SqlDbType.NVarChar).Value = cmbEmp.SelectedItem.ToString();

 the same i want to convert and read from excel or ini.

How to change..?
0
Hello Experts,
I would like to know if there are any PC utilities to read CSV files other than Excel. I see a host of them online, but I would really like your recommendation based on your personal experiences.
0
I have formula filed f1 do (field1-feld2) during tow dates
then how to use something like this in my c# code
DB db = new DB();
            DateTime StartDate;
            DateTime EndDate;
            StartDate = Convert.ToDateTime(dtpfrom.Value.ToString("yyyy-MM-dd"));
            EndDate = Convert.ToDateTime(dtpto.Value.ToString("yyyy-MM-dd"));
            FrmViewer fv = new FrmViewer();
            crtunderMedicineRoof rpt = new crtunderMedicineRoof();
            string sql = "";
            sql = "  {View1.MedicineDate}in #" + StartDate + "# to #" + EndDate + "#";
            param = "سقف العلاج للفترة من  " + " " + dtpfrom.Value.ToString("yyyy-MM-dd") + " الي" + " " + dtpto.Value.ToString("yyyy-MM-dd");
                        //
            if (ckb_overRoof.Checked == true)
                sql += "and  View1.f1<0)";//using formula field here
            rpt.SetParameterValue(0, param);
            //rpt.SetParameterValue(1, p);
            rpt.RecordSelectionFormula = sql;
            rpt.SetDatabaseLogon("cost", "cost");
            fv.crystalReportViewer1.ReportSource = rpt;
            fv.Show();
0
in my case i use more than form tag in usercontrol and each form has some controls with validations and the validation works fine but when i try to call codebehind method the button don't fire the event

here is example of my code in user control
<form data-toggle="validator" role="form">


<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>






<div class="form-group">
<label for="DDL_Comp_Baladya">البلدية</label>
<select class="form-control" id="DDL_Comp_Baladya" runat="server">
</select>
</div>


<div class="form-group">
<label for="DDL_Comp_Baladya">الإدارة</label>
<select class="form-control" id="DDL_Comp_Management" runat="server">
</select>
</div>




<div class="form-group">
<label for="txt_Comp_Name" class="control-label">الاسم</label>
<input type="text" class="form-control" id="txt_Comp_Name" runat="server" placeholder="الاسم" data-required="عفواَ من فضلك ادخل الاسم !!" required>
</div>


<div class="form-group has-feedback">
<label for="txt_Comp_Phone" class="control-label">الهاتف</label>

<input type="text" pattern="[0-9]+" title="" maxlength="10" class="form-control" id="txt_Comp_Phone" runat="server" placeholder="الهاتف">
</div>


<div class="form-group has-feedback">
<label for="txt_Comp_ID" class="control-label">السجل المدني / الأقامة</label>

<input type="text" pattern="[0-9]+" title="" maxlength="10" class="form-control" id="txt_Comp_ID" runat="server" placeholder="السجل المدني / الأقامة" required>
</div>


<div class="form-group 

Open in new window

0
Technology Partners: We Want Your Opinion!
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

I have xml file and I want to load the xml using JavaScript datatable

https://editor.datatables.net/examples/advanced/REST.html

Do you know how to do that?
0
Is it possible to modify a DataGridView and for columns that correspond to multiple values in a database table ... provide the values in a combo box control so the end user can select which value they want at runtime?  Along with this I am also wanting a way to update the datasource so that the selections are preserved in the DataGridView until they are committed to the database.

Looking for some great examples for doing this.

C# Windows Form application, not web.
0
I have a piece of code that works fine in a windows executable but when I move the same code to a web services it fails with:
"The request was aborted: Could not create SSL/TLS secure channel."
see the below code where I wrote "FAILS"

               ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                HttpWebRequest req1 = (HttpWebRequest)WebRequest.Create("https://thewebsite?wsdl");

                req1.ContentType = "text/xml; charset=\"utf-8\"";
                req1.Accept = "text/xml";
                req1.Method = "POST";

                System.Security.Cryptography.X509Certificates.X509Certificate2 x = new System.Security.Cryptography.X509Certificates.X509Certificate2("D:\\tlr\\TLR.crt", "");
                req1.ClientCertificates.Add(x);

                using (Stream stm = req1.GetRequestStream())
                {
                    using (StreamWriter stmw = new StreamWriter(stm))
                    {
                        stmw.Write(oRequest);
                    }
                }

                IAsyncResult asyncResult = req1.BeginGetResponse(null, null);

                asyncResult.AsyncWaitHandle.WaitOne();

                string soapResult = "";
                using (WebResponse webResponse = req1.EndGetResponse(asyncResult)) // FAILS!
                {
                    using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
                    {
                 …
0
We have a GPS tracking app
There is one windows app on windows server 2016 which communicates with the gps devices on different ports and accepts the data

We have recent seen problems where the gps devices stop reporting, even though they are constantly sending data every 30 secs  (some are saying 6 hours ago)

When we restart the windows app, they start reporting again within 30 seconds

We have 2 devices working on port a certain port
However, when looking at netstat, its showing 62 connections, and they are all ESTABLISHED
This sounds like its the cause of the issue

C:\Windows\system32>netstat -a -n | find /c "3333"
62

Open in new window


 TCP    82.113.146.43:3333     41.80.64.186:50270     ESTABLISHED
  TCP    82.113.146.43:3333     105.48.38.41:49817     ESTABLISHED
  TCP    82.113.146.43:3333     105.50.155.210:51853   ESTABLISHED
  TCP    82.113.146.43:3333     105.51.186.160:54257   ESTABLISHED
  TCP    82.113.146.43:3333     105.51.233.133:59692   ESTABLISHED
  TCP    82.113.146.43:3333     105.54.2.101:57306     ESTABLISHED
  TCP    82.113.146.43:3333     105.57.244.173:52367   ESTABLISHED
  TCP    82.113.146.43:3333     105.57.249.109:50983   ESTABLISHED
  TCP    82.113.146.43:3333     105.58.227.38:53840    ESTABLISHED
  TCP    82.113.146.43:3333     105.59.87.117:64881    ESTABLISHED
  TCP    82.113.146.43:3333     105.59.254.162:55759   ESTABLISHED
  TCP    82.113.146.43:3333     105.61.81.156:60019    ESTABLISHED
  TCP    82.113.146.43:3333     

Open in new window

0
Hello Experts,
I am testing a newly developed windows service and need to see how it handles system exceptions (something like outofmemory, etc). Is it possible to simulate any such occurrences from outside (without modifying the underlying code)? Please suggest.
0
assume i have xml like

<People>
<Person>
 <First>John</First>
<Last>Smiths</Last>
</Person>
</People>

Open in new window


And i have xyz.pdf and have field name="First" and field name="Last"
In c#, I know I can use itextsharp to fill up the pdf. But I do not want how to read and map the fields.
My goal is to extract <element>Value</element>, and map the field name in pdf, and send email to someone

Thanks
0
I have a simple Gridview and Formview set up on a couple of different pages. I use the FormView to edit existing records in the GridView or to add a new record. It works perfectly on one page, but on another one when I select the record in the Gridview that I want to edit in the FormView, I keep getting this error message:
'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value

Open in new window

I can run SELECT DISTINCT WHS FROM AER_DOCK_APPOINTMENTS and I get three returned entries, each two characters long. In the DropDownList on the page, I have those same three two-character long choices as ListItems. The Insert from the FormView works perfectly.

CODE FOR DROPDOWN ON PAGE THAT WORKS
<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind("WAREHOUSE") %>'>
                                <asp:ListItem Selected="True"></asp:ListItem>
                                <asp:ListItem>LB</asp:ListItem>
                                <asp:ListItem>LP</asp:ListItem>
                                <asp:ListItem>SN</asp:ListItem>
                                <asp:ListItem>SS</asp:ListItem>
                                <asp:ListItem>WA</asp:ListItem>
                            </asp:DropDownList>

Open in new window


CODE FOR DROPDOWN ON PAGE THAT DOES NOT WORK
<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind("WHS") %>'>
                                <asp:ListItem Selected="True"></asp:ListItem>
                                <asp:ListItem>LB</asp:ListItem>
                                <asp:ListItem>SN</asp:ListItem>
                                <asp:ListItem>SS</asp:ListItem>
                            </asp:DropDownList>

Open in new window


What am I missing to figure this out?
0
The codes below is working ok. I just need to make VAR response to be sorted.
How can I do that?

   public static List<Make> GetVehicleMakeList()
        {
            List<Make> lstMake = new List<Make>();
            HttpClient objClient = new HttpClient();
            try
            {
                var response = objClient.GetStringAsync(Utility.Enumeration.vehicleMakeAPICall).Result;
                if (!string.IsNullOrEmpty(response))
                {
                    VehicleMakeAPIResponse objMakeResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<VehicleMakeAPIResponse>(response);
                    return objMakeResponse.Results;
                }

            }
            catch (Exception ex)
            {

                //log error message here
            }
            return lstMake;
        }

Open in new window

0
Hi Experts,
I use Crystal Reports in my C#.Net Windows Service.
When I run my app, I get the error below:

ERROR
The type initializer for 'CrystalDecisions.Shared.SharedUtils' threw an exception.

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its dependencies.
The system cannot find the file specified.



I do see CrystalDecisions.Shared.dll in my Windows bin folder.

How can I resolve this issue?

Thank you in advance,
mrotor
0
Free Tool: Subnet Calculator
LVL 11
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Hi Experts,
I need help checking for null values in my C#.Net program.

Here is a sample of my code, how would I check for null values in order to prevent my program from crashing?

SAMPLE CODE:
PatientLName = reject.PatientLName.ToString();

Open in new window


Thank you very much in advance,
mrotor
0
i am facing issue i have radiobutton with different time slot and i want to disable radio button list item if system current time is more than radiobutton list item.
 
I am getting error input string is not in correct format..
 
What I have tried:
 
<pre>  string id = Request.QueryString["id"];
        txtdate.Text = Calendar1.SelectedDate.ToShortDateString();
        Calendar1.Visible = false;
       
      //  DateTime txtMyDate = DateTime.Parse(txtdate.Text);
        SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        string Query = "select slot from appoint where selectdate = @date and doc_id='"+id+"'";
        SqlCommand cmd = new SqlCommand(Query, cnn);
        cmd.Parameters.AddWithValue("@date", txtdate.Text);
        DataTable dtAdmin = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dtAdmin);
        if (dtAdmin.Rows.Count > 0)
        {
            string[] slots = dtAdmin.Rows.OfType<DataRow>().Select(k => k["slot"].ToString()).ToArray();
            string time = DateTime.Now.ToString("HH:mm tt");
 
            foreach (ListItem item in RadioButtonList1.Items)
                if (slots.Contains(item.Text) && Convert.ToInt32(item.Text) < Convert.ToInt32(time))
                {
               
                        item.Enabled = false;
                   
                }
                else
                {
         …
0
Hi,

Once again coming from a beginner perspective so I can start to do some reading for curiosity.

I know that ASP.NET core web apps have to handle things to handle different screen sizes. For example a client might
browse from a phone or a PC or a tablet.

How is this detected and handled basically.

What term should I be looking for in the documentation and tutorials to see how this is approached.?

Also really to ask how difficult this is to code and handle in general.

Thanks,

Ward
0
Hi,

I am using datagridview.

i just want to update the combobox cell value. i cell value should update based on my condition.

But, the problem is, combobox value displaying which is last executed value only always. the remining condition is updating the cell.

what is the problem in my code.

sample data.

EMPNO      STATUS (Dropdown)
101      1-EXCELLENT 2-MODERATE
102      1-EXCELLENT 2-MODERATE 3-GOOD 4-AVERAGE
103      1-EXCELLENT 2-MODERATE 3-GOOD 4-AVERAGE
104      1-EXCELLENT 2-MODERATE
105      1-EXCELLENT 2-MODERATE 3-GOOD 4-AVERAGE
106      1-EXCELLENT 2-MODERATE 3-GOOD 4-AVERAGE

List<string> Emplist = new List<string>(); 
foreach (DataRow row in dt.Rows)
 {
         Grid1.Rows.Add();
         Grid1[0, cnt].Value = row["EmpNO"].ToString();
         Grid1.UpdateCellValue(0, cnt);
         DataGridViewComboBoxCell cbobox = (DataGridViewComboBoxCell)Grid1[1, cnt];
	 
	 if (cbobox.Items.Count == 0)
         {
		// Conditions
	   
	 if ((Mark1 != 0) && (SUB == "H1"))
         {
             Emplist.Clear();
             Emplist.Add("1-EXCELLENT");
             Emplist.Add("2-MODERATE");
             cbobox.DataSource = Emplist;
             Grid1.UpdateCellValue(3, cnt);

         }
	 else if ((Mark2 != 0) && (SUB2 == "H2"))
         {
             Emplist.Clear();
             Emplist.Add("1-EXCELLENT");
             Emplist.Add("2-MODERATE");
	     Emplist.Add("3-GOOD");
             Emplist.Add("3-AVERAGE");
             cbobox.DataSource = Emplist;
             

Open in new window

0
Hi Experts,

I am using below C# code to remotely login to a machine in domain say D2 from my local machine in domain D1. When i use MSTSC and pass correct credentials, I am able to get into. But using below code, I get inner exception "Access Denied" and parent exception as  "Could not connect to remote machine". I am able to ping remote machine from my machine and also ensured that remote registry servcie is up and running on remote machine.The accounts are different for my local and remote machine. What am i missing? If its access of local machine or local account on remote, what exact steps need to be followed to get it done.


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 public static class ProcessExtensions
    {
        public static void KillRemoteProcess(this Process p, string user, string password)
        {
            new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "TaskKill.exe",
                    Arguments = string.Format("/pid {0} /s {1} /u {2} /p {3}", p.Id, p.MachineName, user, password),
                    WindowStyle = ProcessWindowStyle.Hidden,
                    CreateNoWindow = true
                }
            }.Start();
        }

        public static void KillProcessesRemote()
        {
            string targetProcessName = "EXCEL"; //Do not put…
0
i have refered many of the links i'm not getting  how to do ,i need get the real height ,width and distance of object from camera like how face detection 'll work ,lf i put mark on object on image while taking picture i need to get all the values on the screen of camera of android phone
 

please let me know how i can do this exactly
0

C#

92K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).