.NET Programming

132K

Solutions

38K

Contributors

The .NET Framework is not specific to any one programming language; rather, it includes a library of functions that allows developers to rapidly build applications. Several supported languages include C#, VB.NET, C++ or ASP.NET.

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

Sign up to Post

Example contrived for this question.  I am following a tutorial in .NET for the  Datacontract XML serialization and deserialization.  I created an interface, a base class for serialization.

public interface ISerializer {
        string Serialize(object obj, Type objType);
        object Desrialize(string serializedData, Type objType);
    }

 public abstract class Serializer : ISerializer {
        public string Serialize(object obj, Type objType) {
            MemoryStream ms = new MemoryStream();
            DataContractSerializer ser = new DataContractSerializer(objType);

            ser.WriteObject(ms, obj);

            ms.Position = 0;

            return new StreamReader(ms).ReadToEnd();
        }

        public object Deserialize(string serializedData, Type objType) {
                   //code to deserialize
        }
    }

and for now, I have a XmlDataContractSerializer class, which uses base classes implementation for serializing data.

public class XmlDataContractSerializer : Serializer {
}

I used XSD tool to generate a class from an XSD file - sample below

using System.Xml.Serialization;
// This source code was auto-generated by xsd, Version=4.6.1055.0.
namespace SampleProject {

        /// <remarks/>
        [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
        [System.SerializableAttribute()]
        [System.Diagnostics.DebuggerStepThroughAttribute()]
        …
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,

I'm just wondering why I can't get specific error messages anymore in Visual Studio when an exception occurs.

For example, I know where this error occured because I'm working in that section of the application, but it used to highlight the line and tell me exactly what caused the problem, now I get a generic error like this:

An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "" to type 'Double' is not valid.

It no longer specifies the line number or highlight the error,

I attached a print screen

Thank you for the help!
printScreen.png
0
Hi Experts! I am once again asking for help on how to do something in .net (Visual Studio) for a client who has an application they use for accessing the UPS website through an API.

UPS has upgraded all their servers and have deprecated support for TLS1.0. Here is a link to more information about this issue: https://www.ups.com/us/en/help-center/technology-support/data-security.page

I need to reference the TLS 1.1 or 1.2 protocols and re-build this application for them. I need some direction on #1 - how to find the correct reference file and #2 how to make the change (which I think I may have figured out how to do)

Any direction will be appreciated.

Thanks a lot!

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.

************** Exception Text **************
System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Authentication failed because the remote party has closed the transport stream.
   at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at …
0
I need something similar to Telerik RadEditor

It needs to "squeeze down" the html on save without all of the tabs, line spacing and carriage returns

Using on a .Net 4.0 web page  Default.aspx

Will code behind on the C#
0
I'm new to ASP.NET MVC development and I have a question regarding Business Logic.  Specifically, where should the Business Logic live in my application.

Just to give you a bit more information about my current MVC application structure, I've decided to go with a Unit of Work Design Pattern and the Repository Design Pattern for my Data Access Layer.  This was chosen to allow flexibility as the data source may be changing and we want to make the application decoupled from it's original data source.

Here's a business logic scenario I have and I'm questioning where it should live.  

I need to gather information from 3 individual tables in my database, perform some calculation on that data (and in some cases merge some data) and return the matching row(s) to my Controller so that can be displayed in my View.  

In my search to discover where to put this logic I was pointed in several different directions.  For example:

- Your business logic should be placed in the Model, and you should be aiming for fat models.
- Most of your logic goes in the MVC controller
- Controller shouldn't have any logic and should be "thin"
- You should create a "Service Layer" and put your Business Logic there.

I'm lost.  Help.
0
I am needing to compare values in two lists which are different types. What I need to do is find out if the AttendeeID is in both lists. If it is in both lists then do nothing, however, if the AttendeeID is not in both lists then we need to add that information to another list. I was trying to use LINQ to do this, however, I'm not doing something correctly and I'm not sure as to where I'm wrong. Below is the code that I currently have.

If TypeOf e.Item Is GridDataInsertItem Then
        
            'Remove individuals from list if they exist already in the outcome memos table before binding the list.
            Dim newClients As RadDropDownList = CType(e.Item.FindControl("rdlClientNames"), RadDropDownList)
            Dim getAllClients As New IndividualsBase
            Dim indList As List(Of IndividualsBase) = getAllClients.SelectIndividuals(0,True,Nothing,0)

            Dim getIndividuals As New OutcomesMemos
            Dim indMemo As List(Of OutcomesMemos) = getIndividuals.SelectOutcomeMemos("Active")
            Dim totalInds As List(Of IndividualsBase)

            indMemo = indMemo.Where(Function(xMemos) Not indList.Contains(xMemos.AttendeeID)).ToList()

            If totalInds.Count = 0 Then
                Dim list As New RadDropDownList
                list.Items.Item(0).Text = "All Individuals Have Been Added"
            Else
                newClients.DataSource = totalInds
                newClients.DataTextField = "FullNameID"
                

Open in new window

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
hello everyone i create one app.config file store in appsettings multiple username and password ?how can i store ? i just see in appsettings key and value and mention also key=username and value=some-pcusername or but i didn't get anything.
                    foreach (var key in appSettings.AllKeys)
                    {
                       //here i want to code with help of storing username and passowrd in appsettings i want to get information of that system
                    }
thank you !
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
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
Hire Technology Freelancers with Gigs
LVL 11
Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Hi,
I cannot show the message prompt properly, by the following. Why?

function showMsg0() {
    $.message({
        title: '信息',
        content: 'new或NEW是保护字,不可以选为名字简称!',
        buttons: {
            OK: {
                text: 'OK',
                btnClass: 'btn-green',
                keys: ['enter'],
                action: function () {
                    //$.alert('You clicked OK!');
                }
            },
        }
    });
    return false;
};
...
        protected void userabbr_post_change(object sender, EventArgs e)
        {
            if (tb_userabbr.Text.ToUpper() == "NEW")
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "showMsg0()", true);
                tb_userabbr.Text = "";
                return;
            }
        }

Open in new window

0
Hi

Are there any cloud accounting packages that have a .Net SDK  or API?

Thanks
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 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
Can you give me example or idea on how to make this happen? Thank you.
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
Dear Experts,
Please suggest how to set tab indexing for asp .net input controls in asp.net
0
I have a lawyer client who's having a problem with a 3rd party program, CaseMap, and .Net Framework 3.5.

His Windows 10 computer was a free upgrade from Windows 7, and is attached to a Server 2012 R2 domain.

When he tries to do a search in CaseMap he gets an error from CaseMap telling him there's a problem with .net 3.5.

I've done various uninstalls and reinstalls of .net 3.5 to no avail. CaseMap has also been uninstalled and reinstalled multiple times, including the last time allow it to reinstall .net 3.5. None of this has worked!

CaseMap tech support has told my client to reinstall Windows 10. This of course would be expensive because the free Windows 10 upgrade is no longer available, plus there'd be my time to basically setup a new computer.

I've attached CaseMap error message DotNet.jpg, and the detail, DotNet2.jpg.

BTW, I know nothing about CaseMap, so my client, a very computer knowledgeable guy, takes care of the CaseMap installations and talking to their tech support.

Am I certain it's not really a CaseMap problem? Of course not!

We've run out of ideas, and would appreciate any suggestions.

Thanks

Mark
DotNet1.JPG
DotNet2.JPG
0
Get free NFR key for Veeam Availability Suite 9.5
LVL 1
Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

So not sure if it related to Patch Tuesday or not, but after I updated my computer Powershell ISE stop working.
I have search the internet for fixes and tried them.
  1. MalwareBytes for Poweliks and nothing came up
  2. Installed PS 5.1
  3. Checked and confirmed that KB3163245 is installed, but this was well before I started to have this issue. I did uninstall it, but still having the same issue.

Any Ideas
0
Hello,
Sorry for my very limited English, i'm french.

Having a concern with a security dll provided by an external company, it responds too slowly in VB.net, 30 to 50 seconds which is unacceptable.

I am trying to create an application that would be hidden at boot time with a notifyicon and a dynamically create menu. This software would be the security management of our other software.

I then need my other software to interoperate the security dll management software, to allow the application to start and retrieve the access levels. (user / super user / admin)

I manage to manage the security part dll. My software recover all the information.

But for now I am trying to overcome two problems:
1) The dynamic creation of the notifyicon and the contextmenustrip. I can create the notifyicon, but the menu does not appear.
2) The dialogue between the 2 software. I found a tutorial to use remoting. It works perfectly, but from a console application, hence the dynamic creation of the notifyicon and contextmenustrip.

I will need a form in my management application. So I tested by creating a form with the notifyicon and the contextmenustrip.
I instantiate the form, without displaying it, and I add a menustrip to my contextMenu, but again I have the icon, but not the menu.

Code below:
 Public Shared Sub Main(ByVal args() As String)
        Try
            ' Création d'un nouveau canal d'écoute sur le port 1069
            Dim channel As TcpChannel = New 

Open in new window

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
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
I need help with my ASP.NET MVC application hosted on iis. The application loses connection to MYSQL database after sometime and requires me to restart mysql service then it continues to connect.
0
say, I have controller method and a corresponding view (see below).

once I load the view, I have a self invoking JavaScript function, that calls the same controller method.
code below, shows the get request, when I test this, I get the value of 1 in the id parameter of my ProcessData method.
in Get request, the data is passed in the query string, which is mapped to my parameter name by ASP.NET ( I guess by the process of model binding). I understand this part.

My question is, if i wanted to do a post request and send a XML data over to the same controller method, how can I achieve this.

In a post request, how do we read data in the controller?

controller -
public ActionResult ProcessData(string id) {          
      return View();
}

view -

@{
    ViewBag.Title = "test";
}

<h2>test</h2>

@section scripts {
    <script type="text/javascript">
        (function () {
            $.ajax({
                type: "Get",
                url: '@Url.Action( "ProcessData", "Test")',
                contentType: "application/xml; charset=utf-8",
                data: {id : 1},              
                success: successFunc,
                error: errorFunc
            });
            function successFunc(data, status) {
                alert('success');
            }
            function errorFunc() {
                alert('error');
            }
    })();
    </script>
}
0

.NET Programming

132K

Solutions

38K

Contributors

The .NET Framework is not specific to any one programming language; rather, it includes a library of functions that allows developers to rapidly build applications. Several supported languages include C#, VB.NET, C++ or ASP.NET.