Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

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

I have the below datamodel.  In MyForm.GetData it is only looping once even though there are 3 rows.  How do i get it to loop and get all the data.

public class DurationModel
{
	public string Duration { get; set; }

	public IEnumerable<List<DurationModel>> GetDurationItems()
	{
		List<DurationModel> durationItems = new List<DurationModel>();

		durationItems.Add(new DurationModel()
		{
			Duration = "1 Day"
		});

		durationItems.Add(new DurationModel()
		{
			Duration = "1 Week"
		});

		durationItems.Add(new DurationModel()
		{
			Duration = "1 Month"
		});

		yield return durationItems;
	}
}

public class MyForm
{
	private ObservableCollection<string> _durationItems = new ObservableCollection<string>();
	private IEnumerable<List<DurationModel>> _durationModel = new DurationModel().GetDurationItems();

	public MyForm()
	{
		GetData();
	}
	
	private void GetData()
	{
		foreach (var items  in _durationModel)
		{
			_durationItems.Add(items[0].Duration);
		}
	}	
}

Open in new window

0
Get your problem seen by more experts
LVL 11
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Below is a mock up of some code.  I have a PopulateModels method.  It is dynamically populating the models.  How do you refactor to remove the code from MyForm?

public class PersonModel
{
	public int PersonID { get; set; }
	public string FristName { get; set; }
	public string LastName { get; set; }
	public datetime DOB { get; set; }
}

public class CourseModel
{
	public int PersonID { get; set; }
	public int InstructorID { get; set; }
	public string CourseName { get; set; }
	public datetime CourseDate { get; set; }
}

public class MyForm
{
	private List<PersonModel> _person = new List<PersonModel>();
	private List<CourseModel> _courses = new List<CourseModel>();

	public MyForm()
	{
		PopulateModels();
	}
	
	private PopulateModels()
	{
		int count = 0;
		DateTime addDays = new DateTime(2017, 06, 01);

		_person.Add(new PersonModel()
		{
			PersonIDID = 1,
			FirstName = "John",
			FirstName = "Doe",
			DOB = DateTime(1992, 03, 21);
		});

		for (int i = 0; i < 10; i++)
		{
			_courses.Add(new CourseModel()
			{
				PersonIDID = 1,
				InstructorID = count++,
				CourseName = GetCourse(count);
				CourseDate = addDays.Date.AddDays(days)
			});


			if (count == 5)
				count = 1;

			count++;
			days += 3;
		}	
	}
	
	//More Methods
}

Open in new window

0
I am using VS2017 to publish a C# function app to Azure. Within that function, I have the nuget module Renci ssh.net that I use to retrieve and delete files from an SFTP server. This process works fine when executed from my local machine in debug. When I publish to Azure and run, I get...

C# Timer trigger function executed at: 1/15/2018 5:00:00 PM
Exception while executing function: GetCSVImportOrders
Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function: GetCSVImportOrders
  ---> System.Net.WebException : The underlying connection was closed: An unexpected error occurred on a send.
  ---> System.IO.IOException : Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
  ---> System.Net.Sockets.SocketException : An existing connection was forcibly closed by the remote host
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer,Int32 offset,Int32 size)
   End of inner exception


...how can I get my Azure FunctionApp to utilize this module or otherwise communicate with my SFTP server? There are no firewall rules between them as the SFTP server does the authentication and the credentials are the same as my local pc. The SFTP server is not even showing a connection attempt so something is preventing the Azure Function App from communicating. I have had no problem with a similar app in the same container talking to a SQL Server on the same server that hosts the SFTP …
0
I have a c# program I am working in that I did not originally create.  I need to add an email element that will create a PDF with graphics (like the attached) authenticate with an email server (like gmail, microsoft or similar) and send that email to a specified address.

I am not sure where to begin, especially on creating the data based graphic.

Thanks.
weeklyemailpdf.jpg
0
I have an input panel with several textboxes and a DBGrid. This is connected to binding source to 2 joined tables (a parent - child one-to-many on a RID field in both tables) This was originally developed to view entered records, but now the client wants to be able to edit all the data in the joined tables, including the RID fields. The first concern is if the RID gets changed in the textbox, the rows have to have the RID column changed after the textbox edit. The RID field is hidden in the grid.

Secondly, they also want the ability to add new records in this form as well. At this point, upon an add new row, the value of the RID textbox needs to be inserted into the hidden RID field in the grid for the first row, and each consecutive row added (there can be any number of rows) So basically, OnAddNew in the grid needs to set Column RID.Value = TextBoxRID.value. Now to add a twist, lets say the user enters the new RID in the textbox, then enters several rows in the Grid, and goes back and changes the Textbox RID, there needs to be a routine that will update the RID column fields in the Grid when the textbox change has been completed. I don't want to check/change on every keystroke in the textbox, but maybe on a lostfocus?

Keep in mind that these fields (textbox & grid) are bound to a dataset via a BindingSource and aTableAdapter.

Any help would be appreciated.
0
We have a huge list (say 100,000) which needs to be converted to DataTable for SqlBulkcopy.

Can you guide what could be the fastest way to do this without using for loop? For now we are doing it like - in below code listDos is object list

using (var dataTable = new DataTable(dataTableName))
{
    dataTable.Locale = CultureInfo.CurrentCulture;
    var columns = new[]
        {
             new DataColumn("Id", typeof(int)),
             new DataColumn("FkId", typeof(int)),
             new DataColumn("Status", typeof(string)),
             new DataColumn("RecordFrom", typeof(DateTime))
        };

    dataTable.Columns.AddRange(columns);


    foreach (ObjectDo listDo in listDos)
    {
        var row = dataTable.NewRow();

        if (rebuildDo.Id != null) row["Id"] = rebuildDo.Id;

        if (rebuildDo.FkId!= null) row["FkId"] = rebuildDo.FkId;

        row["Status"] = rebuildDo.Status;

        row["RecordFrom"] = rebuildDo.RecordFrom;

        dataTable.Rows.Add(row);
    }

    return dataTable;
}

Open in new window

0
Here i am getting firebase id token ,and it works fine-
public async override void OnTokenRefresh()
{
refreshedToken = FirebaseInstanceId.Instance.Token;
SendRegistrationToServer(refreshedToken);
}

Open in new window


but how to generate this token only when user login to the app(after click on login button)?
give me sample code for do this.
0
I have an html view...which has a template....
Note the use of display none.  
This template is used to inject a row into my datatable.

The problem with this is ....later on I have javascript that needs to find this control on the page...and it cannot because
Both template and the row added are rendered in html...

I need some way of appending an ID value to the controls when the row is added to the datatable...

Please help.


Here is template on my view:

<table id="new-row-template" style="display:none">
        <tbody>
            <tr>
                <td>
                    <label></label> 
                </td> 
                <td>
                   @Html.DropDownList("ddlRole", new SelectList(ViewBag.DDLRoles, "Value", "Text"), "")
                </td>
                <td>
                    @Html.DropDownList("selectdesignate", new List<SelectListItem>
                    {
                        new SelectListItem{ Text="", Value = ""  },
                        new SelectListItem{ Text="Primary", Value = "Primary" },
                        new SelectListItem{ Text="Secondary", Value = "Secondary" },
                     })                 
                </td>
                <td> 
                   @Html.TextBox("txtAllocation", new { @class = "form-control", @type = "number" })         
                </td>
                <td>
                    <button type="button" id="btnInsertContactEntity" class="btn btn-primary btn-xs 

Open in new window

0
Hello,
I'm trying to change the height and width of some divs, at runtime, but I haven't had much luck so far.

this my source code

 <div id="divImgContainer" style="height: auto; width: 1000px; overflow-y: scroll; display: inline" runat="server">


           <div id="divImg" style="height: 900px; width: 640px; overflow: auto; float: left;" runat="server">

               <asp:UpdatePanel runat="server" ChildrenAsTriggers="False" UpdateMode="Conditional" ID="upnlMainImage">
                   <ContentTemplate>
                       <asp:Image runat="server" ID="img"
                           ImageUrl=""
                           Height="900px" Width="640px" BorderStyle="Solid" BorderWidth="2px" BorderColor="Red"></asp:Image>
                   </ContentTemplate>
               </asp:UpdatePanel>
           </div>

           <div id="divResult" style="float: left;" runat="server">
               <asp:UpdatePanel runat="server" UpdateMode="Conditional" ID="upnlTicks" ChildrenAsTriggers="False">
                   <ContentTemplate>
                       <asp:Panel ID="pnlResult" runat="server" Height="900px" GroupingText="Mark Here" Width="320px">
                           <asp:Label ID="lblResults" runat="server" Text=""></asp:Label>
                           <asp:Repeater ID="rptResults" runat="server" OnItemCommand="rptResults_ItemCommand" OnItemDataBound="rptResults_ItemDataBound">
                               <ItemTemplate>
                            

Open in new window

0
Hi, I'm changing the class at runtime of a table (tblzoom) which is inside a repeater. However the changes are not kept after postbacks.
 <div id="divImgContainer" style="height: auto; width: 1000px; overflow-y: scroll; display: inline">

           <div id="divImg" style="height: 900px; width: 640px; overflow: auto; float: left;">

               <asp:UpdatePanel runat="server" ChildrenAsTriggers="False" UpdateMode="Conditional" ID="upnlMainImage">
                   <ContentTemplate>
                       <asp:Image runat="server" ID="img"
                           ImageUrl=""
                           Height="900px" Width="640px" BorderStyle="Solid" BorderWidth="2px" BorderColor="Red"></asp:Image>
                   </ContentTemplate>
               </asp:UpdatePanel>
           </div>

           <div id="divResult style="float: left;">
               <asp:UpdatePanel runat="server" UpdateMode="Conditional" ID="upnlResults" ChildrenAsTriggers="False">
                   <ContentTemplate>
                       <asp:Panel ID="pnlResult" runat="server" Height="900px" GroupingText="Mark Here" Width="320px">
                           <asp:Label ID="lblResults" runat="server" Text=""></asp:Label>
                           <asp:Repeater ID="rptResults" runat="server" OnItemCommand="rptResults_ItemCommand" OnItemDataBound="rptResults_ItemDataBound">
                               <ItemTemplate>
                                   <table class="nozoom" id="tblzoom" 

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 am making the project in c# form.n i have no idea how to take the input from the bar code scanner and show it on the text box.i don't even know that .what is the output of the barcode scanner.?kindly help me in making the structure. and bar code scanning..Thank you.!
0
I have the below code that works.  I want it to validate two properties.
ViewChartCommand = new DelegateCommand(OnViewChartCommandExecute,(() => !(String.IsNullOrEmpty(_duration) ))).ObservesProperty(() => (SelectedDuration));

Open in new window

I tried to implement this but it looks like it is not working.
ViewChartCommand = new DelegateCommand(OnViewChartCommandExecute,(() => !(String.IsNullOrEmpty(_duration) || String.IsNullOrEmpty(_diagnostic)))).ObservesProperty(() => (SelectedDuration)).ObservesProperty(() => SelectedDiagnostic);

Open in new window

How do I check two properties?
0
I have a view...that build a few controls...and has two buttons..with JS events..that need to pass the values from the view in the  javascript function calls..

Please help.


Here is the section of the view where the controls are defined mostly.  My insert call for example here need to pass the contactid..which will be on a hiddenfield passed into the page from another page when this page is rendered.
The other values the user will select.  One is a dropdownlist populated from my controller/model.
The other is a dropdown with static values.
ANd finally the last column is just a decimal value input on screen.
There is also a client value passed fro mthe user selection of an autocomplete dropdown...not seen in this view.  Those values all need to go in my insert ...which is just an ajax call back to a controller method from javascript.

 <table id="new-row-template" style="display:none">
        <tbody>
            <tr>
                <td>
                    <label></label> 
                </td> 
                <td>
                   @Html.DropDownList("DropDownListID", new SelectList(ViewBag.DDLRoles, "Value", "Text"), "--- Please Choose an Item! ---")
                </td>
                <td>
                    <select id="selectdesignate" name="selectdesignate" class="form-control">
                        <option value="1"></option>
                        <option value="2">Primary</option>
                        <option 

Open in new window

0
I am writing an app and I'm trying to perform a test.

    public class PatientDiagnostics
    {
        public int PersonID { get; set; }
        public int HeartRate { get; set; }
    }

Open in new window


I would like to dynamically change the heart rate.  Start off with HeartRate = 20.  Then increase and decrease it +/- 2, 3.
0
Develping a xamaring form.  Using Prism.  Have View and View Model.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms" 
             prism:ViewModelLocator.AutowireViewModel="True" 
             x:Class="MylApp.Views.ViewSelectionPage"
             Title="Selection">

  <StackLayout Padding="0,20,0,0">

      <!--x:Name="DurationPicker"-->
      <Picker 
              HorizontalOptions="FillAndExpand" 
              Title="Select Duration"  >
          <Picker.Items>
              <x:String>1 Day</x:String>
              <x:String>2 Days</x:String>
              <x:String>3 Days</x:String>
          </Picker.Items>
      </Picker>
  </StackLayout>

</ContentPage>

Open in new window


using System;
using System.Collections.ObjectModel;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
using Prism.Services;
using Xamarin.Forms;

namespace MylApp.ViewModels
{
    public class ViewSelectionPageViewModel : BindableBase, INavigationAware
    {
        private readonly INavigationService _navigationService;

        public ViewChartSelectionPageViewModel(INavigationService navigationService)
        {
            _navigationService = navigationService;
        }

        public void OnNavigatedFrom(NavigationParameters parameters)
        {

        }

        public void OnNavigatedTo(NavigationParameters parameters)
        {

        }

        public void OnNavigatingTo(NavigationParameters parameters)
        {

        }
    }
}

Open in new window


How can I programatically populate the Picker.  How do I get the value selected?
0
I have tried a variety of ways to get running totals in my pivot table.  It works fine for a standard sum.  The variable dataField contains the value "Ledg Amt", which is extracted from my pivot definition table.  When I type the code in my project, I get no red lines.  It seems to be the correct syntax, but when I run it then I get an error.  

No Error - This works fine
                                            pivotTable.AddDataField(dataField,
                                                pivotData + " Summary",
                                                XlConsolidationFunction.xlSum).NumberFormat = "#,###";

Error:  Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))
 
                                           pivotTable.AddDataField(dataField,
                                                pivotData + " Summary",
                                                XlPivotFieldCalculation.xlRunningTotal);

Error:  PivotFields method of PivotTable class failed

                                            pivotTable.PivotFields(dataField).ShowDataAs =
                                                XlPivotFieldCalculation.xlRunningTotal;

Error:  'System._ComObject' does not contain a definition for 'ShowDataAs'

                                          pivotTable.PivotFields(dataField.Name).ShowDataAs =
                                                XlPivotFieldCalculation.xlRunningTotal;

Error:  PivotFields method of …
0
I have two questions about "under the hood" processes executed by Webrequest and the getresponse method.

1) I have noticed while packet capturing that, when doing a webrequest with a payload, packets starting a TCP/IP connection are sent and received *before* the getresponse method?  I would have expected the payload to be cached and sent only when the getresponse was called?

2) I have a webrequest case that has me puzzled.  It is an HTTPS URI.  All proceeds as expected (443 TCP/IP connection made before getresponse called) until the getresponse is called.  When that happens, the process attempts to create a new TCP/IP connection to the server, this one being on port 80 (not HTTPS).  Since the request is not HTTPS, the server ignores it and the process times out with a "no response from server".

What would cause the getresponse method to spawn a new connection, and why would it send it via HTTP when the original connection was made via HTTPS?  The certificate for the server is valid, and I have tried turning off the check-certificate functionality.

Thanks for any insight on both questions.

Bryan Hunt
0
I have a script component where I'm concactenating several strings then inserting the resultant string into a DT_NEXT field.  So I have something like this (s is the string).

if (!Row.chkenvironmentaldatapres_IsNull && !String.IsNullOrWhiteSpace(Row.chkenvironmentaldatapres.ToString()))
            s = s + "Environmental data pres: " + Row.chkenvironmentaldatapres.ToString() + Environment.NewLine;

        if (!Row.smokestatuscode_IsNull && !String.IsNullOrWhiteSpace(Row.smokestatuscode.ToString()))
            s = s + "Smoke status code: " + Row.smokestatuscode.ToString() + Environment.NewLine;

        if (!Row.txttobaccocessdiscuss_IsNull && !String.IsNullOrWhiteSpace(Row.txttobaccocessdiscuss.ToString()))
            s = s + "Tobacco cessation discuss: " + Row.txttobaccocessdiscuss.ToString() + Environment.NewLine;


        Row.SH.AddBlobData(GetBytes(s));

    }

    private byte[] GetBytes(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }

}

Open in new window


The problem is the Environment.Newline isn't working.  My text shows up in the application looking like this:

Categorye One:  Patient Presents with this&#x0D;Category Two: Patient Presents with this&#x0D

I should be seeing:
Category One:  Patient presents with this

Category Two:  Patient presents with this

What should I be using besides Environment.Newline?

James
0
Hi All,

I am looking for either code or a control, which operates in a manner similar to the combo next to the label "Look In" in the image below:

Look in
I am aware of an currently use the BrowseForFolder type control, but its not exactly ideal - my preference is for a combobox that throws out a treeview controlwith the directories listed in the same manner ...

MTIA

DWE
0
Free Tool: Site Down Detector
LVL 11
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

I have inherited a very, very large c# program this displays images using Windows Controls.Add(catalogItem) to display a group of images related to the image that is clicked. What I cannot figure out is how to release the Handles/User Objects when the images are no longer displayed.
My program crashes, of course, when 10,000+ User objects are displayed. No, they are not displayed all at once, but a group of as many as 70 are displayed at one time.
What I would like to do is return/clean up those resources when the [Back] button is clicked.
I have tried using a Controls.Remove(catalogItem) call, and it does remove the picture from view, but it does not release the resources internally.
I am using Visual Studio Community 2017.
Thanks!!!
0
I have code in JAVA can you convert it in C# I want to create RSA SHA256 signature with private key here I have some reference code in java that I am sharing below. I have successful creating RSA sha256 signature using RSACryptoServiceProvider

String version = "2";

if (request.getMethod().equals("GET")) {
 String headerVal = "application/vnd.mobi.lcs.rmw+json; version=" + version;
 request.addHeader("Accept", headerVal);
} else if (request.getMethod().equals("POST")) {
 String headerVal = "application/vnd.mobi.lcs.rmw+json; version=" + version;
 request.addHeader("Content-Type", headerVal);
} else if (request.getMethod().equals("PATCH")) {
 String headerVal = "application/vnd.mobi.lcs.rmw.patch+json; version=" + version;
 request.addHeader("Content-Type", headerVal);
}

String authHeader = generateAuthorizationHeader(request, version);
request.addHeader("Authorization", authHeader);



private String generateAuthorizationHeader(HttpRequestBase request, String version) throws IOException, SignatureException) {
 String token = generateToken(); // Current timestamp and some random numbers

 try {
  this.sig = Signature.getInstance("SHA256withECDSA");
  sig.initSign(this.key);
 } catch (NoSuchAlgorithmException e) {
  throw new Error("No support for SHA256withECDSA! Check your Java installation.");
 } catch (InvalidKeyException e) {
  throw new Error("Invalid EC key!");
 }

 byte[] message = messageTop(request, version, token);
 sig.update(message);

 InputStream 

Open in new window

0
After my category drop down list is selected, it is supposed to show the sub categories of that particular category. However there is an error now!
Below is the code, the commented codes are what worked initially, however now i have to use BllSubCategory, which caused the error to occur
     protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            int MainCategoryID = Convert.ToInt32(ddlCategory.SelectedItem.Value);
            BllSubCategory subCat = new BllSubCategory();
            DataSet ds = subCat.GetSubCatByCatName();
            ddlSubCategory.DataSource = ds;
            ddlSubCategory.DataTextField = "SubCatName";
            ddlSubCategory.DataValueField = "SubCatID";
            ddlSubCategory.DataBind();
            ddlSubCategory.Items.Insert(0, new ListItem("-Select-", "0"));
            ddlSubCategory.Enabled = true;
            /*  int MainCategoryID = Convert.ToInt32(ddlCategory.SelectedItem.Value);
             *  using (SqlConnection con = new SqlConnection(CS))
              {
                  SqlCommand cmd = new SqlCommand("select * from tblSubCategories where MainCatID='" + ddlCategory.SelectedItem.Value + "'", con);
                  con.Open();
                  SqlDataAdapter sda = new SqlDataAdapter(cmd);
                  DataTable dt = new DataTable();
                  sda.Fill(dt);

                  if (dt.Rows.Count != 0)
                  {
                      

Open in new window

0
Hi,

I am using tab and maintaining some validation in every form of the tab.

for example,

In Tab1, i am validating some controls and showing some error. The thing is Error is showing, but immediately it is going to the next tab.

it is not maintaining the same tab to point the cursor.

what is the problem..

see my validation code...

               
foreach (DataGridViewRow item in EmpGrid.Rows)
            {


                if ((item.Cells[4].Value != null) && (item.Cells[4].Value.ToString() != String.Empty))
                {
                    string errstr = "Please Enter Emp Name";
                    System.Windows.Forms.MessageBox.Show(errstr);
                    EmpGrid.CurrentCell = EmpGrid.Rows[item.Index].Cells[5];
                    EmpGrid.Rows[item.Index].Cells[5].Style.BackColor = Color.Blue;
                    break;
                }
}

How could we use in for each loop on button click event...

It means when i click the button it should perform the validation in particular cells.  (not all the cells)...
0
How to add multiple images picture box on panel using c# through coding just like this pic you can see pic and tell me
Capture01.PNG
0
I have a dataset being returned from SQL Server into my web form

It has a column  called BatchNumber that can be from 1 to 1000 rows


I also have a comma seperated string
strMyList = "1,3,5,7"

I would like to remove from strMyList any value not in the "longer list"

So that if the dataset does not have BatchNumber 3 then
strMyList would = "1,5,7"
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).