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 am working on EF6 with MVC5.
The solution is a job manager application.
Here are the data classes

Job class
      Description
      AddressLine1..3
      City
      State
      Zip
      ContractId
      Contract

Contract class
      ContractDescription
      RecruiterID
      RecruitingCompanyID
      RecruitingCompany
      Job


RecruitingCompany class
      CompanyName
      AddressLine1..3
      City
      State
      Zip
      Phone
      ICollection<RecruiterContact>RecruiterContact
      ICollection<Contract>Contracts

RecruiterContact class
      FirstName
      LastName
      RecruitingCompanyID
      RecruitingCompany


The relations need to be as follows:
Job to Contract is 1 to 1
Contract to RecruitingCompany is 1 to 1
RecruitingCompany to Contract is 1 to Many
RecruitingCompany to RecruiterContact is 1 to Many

So,  I will speak to a reqruiter, potentially add the recruiter to the recruiter company or just add to an existing in the DB recruiter company.  The reqruiter gets the contract and the contract is tied to the job.  I think this models the process, but how to build the classes such that EF will build the database/tables/keys/foreign keys and then bootstrapping with some test data is my challenge.

Any suggestions for the data/entity classes and the subsequent bootstrap data would be appreciated.
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'm trying to build a page so it has access to multiple models, doing this using a view model below. The errors happens on the line in the create method that generates a guid and tries to assigned it to ticket.id .. which the viewmodel has a ticket property so I'm think it should work but im clearly missing something.

This is my Controller:

        public async Task<ActionResult> Create([Bind(Include = "Id,StartTime,EndTime,Title,Description,SeverityType")] TicketViewModel model)
        {
            if (ModelState.IsValid)
            {
                model.Ticket.Id = Guid.NewGuid();
                Technician TechnPhone = db.Technician.Find(model.Technician.PhoneNumber);
                model.Technician.PhoneNumber = TechnPhone.PhoneNumber;
                db.Tickets.Add(model.Ticket);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            return View(model);
        }

Open in new window


This is my View:

@model Test.ViewModel.TicketViewModel

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>Ticket</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.HiddenFor(m => m.Ticket.Id)
            
        </div>
        <div class="form-group">
        

Open in new window

0
Im using web service, where the data in project B has to be updated in project A,

Heres how i did for the DAL class in project B
 public DataSet UpdateBook(String baddress, String bpostalcode, String bcountry, String saddress, String spostalcode, String scountry, String bcompany, String bcity, String scompany, String scity)
        {
            int result = 0;
            DataSet updateAdd;
            SqlDataAdapter da;
            string queryStr = "UPDATE CompanyAddress"
                + "SET BillingAddress=@billingaddress, BillingPostalCode=@billingpostalcode, BillingCountry=@billingcountry, ShippingAddress=@shippingaddress, ShippingPostalCode=@shippingpostalcode, ShippingCountry=@scountry, BillingCompany=@billingcompany, BillingCity=@billingcity, ShippingCompany=@shippingcompany, ShippingCity=@shippingcity"
                + "WHERE CompAddressId=@compAddressId";
            SqlConnection conn = new SqlConnection(_connStr);
            updateAdd = new DataSet();
            SqlCommand cmd = new SqlCommand(queryStr, conn);
            try
            {
                da = new SqlDataAdapter(queryStr.ToString(), conn);
                da.Fill(updateAdd);
                cmd.Parameters.AddWithValue("@billingaddress", baddress);
                cmd.Parameters.AddWithValue("@billingpostalcode", bpostalcode);
                cmd.Parameters.AddWithValue("@billingcountry", bcountry);
                cmd.Parameters.AddWithValue("@shippingaddress", saddress);
         

Open in new window

0
Hi
I just started with WPF and the firs problem I found before I wrote a line of the code.
I attached here the picture and I want to know how to remove this black box from the window.
I'm sure it is very easy but I don't know how ).
Capture.PNG
0
Hi

I have used ado.net to return a dataset
I now need to query the dataset with linq

i.e.

int event1Count = ds.where(eventId = 1);
int event2Count = ds.where(eventId = 2);

Open in new window


How can I achieve this ?
0
0
In PropertyGrid, Value is displayed using TypeConverter. In Modal, Value for property "Name" is "Stefan". By using TypeConverter it is displayed as "My Name is : Stefan" In Edit mode (When user clicks on propertyGrid cell) Original value "Stefan" has to be displayed.

Thanks for your feedback.

public Form3()
{
  InitializeComponent();

  var t = new Test();
  t.Name = "Stefan";
  propertyGrid1.SelectedObject = t;
}
public class NameConverter : TypeConverter
{
  public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
  {
    if (value == null)
      return null;

    return "My Name is : " + value;
  }


  public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
  {
    return value;
  }

  public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
  {
    return true;
  }
}

public class Test
{
  // we use a custom type converter
  [TypeConverter(typeof(NameConverter))]
  public string Name { get; set; }
}

Open in new window




Expected Result
0
In PropertyGrid, Value is displayed using TypeConverter. In Modal, Value for property "Name" is "Stefan". By using TypeConverter it is displayed as "My Name is : Stefan" In Edit mode (When user clicks on propertyGrid cell) Original value "Stefan" has to be displayed.

Thanks for your feedback.

public Form3()
{
  InitializeComponent();

  var t = new Test();
  t.Name = "Stefan";
  propertyGrid1.SelectedObject = t;
}
public class NameConverter : TypeConverter
{
  public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
  {
    if (value == null)
      return null;

    return "My Name is : " + value;
  }


  public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
  {
    return value;
  }

  public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
  {
    return true;
  }
}

public class Test
{
  // we use a custom type converter
  [TypeConverter(typeof(NameConverter))]
  public string Name { get; set; }
}

Open in new window



Expected Result
0
  private ObservableCollection<Contact> GetContacts(String SearchText = null)
        {
            _contacts = new ObservableCollection<Contact>
            {
                new Contact{Name = "mosh",Status ="hi",ImageUrl= "http://lorempixel.com/100/100/people/1"  },
                 new Contact{Name = "josh",Status ="halo",ImageUrl= "http://lorempixel.com/100/100/people/2"  }
            };
            if (String.IsNullOrWhiteSpace(SearchText))
                return _contacts;
            else
              return (ObservableCollection<Contact>)_contacts.Where(c => c.Name.StartsWith(SearchText));[/b]
        }
      

Open in new window



while  implementing search  functionality in contacts I  am  getting error  at  lastline.Code  compiles perfectly while  running  gives error.
If  I  make  return  type  IEnumerable  problem  might get solved  but  delete  contact  functionality  might  not refresh  list.
I  have  attached  xaml and  cs  file  to this  question  ,please  help
ContextListPage.xaml
ContextListPage.xaml.cs
0
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
What does it mean to be "Always On"?
LVL 5
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

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
Receive 1:1 tech help
LVL 11
Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

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

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).