C#

93K

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

Need help calling the generic method.

We have a method 'DeserializeToModel' that takes in [a string (an encoded Json) and a reference type] and deserialized it into the reference type model.

public class DeserializedJsonToModel 
  {
      public T DeserializeToModel<T>(string encodedJson, T model) where T : class, new()
      {
          DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings();
          settings.UseSimpleDictionaryFormat = true; //This is needed to read in the dictionary in HospitalAffiliations class

          T deserializedModel = new T();
          MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(encodedJson));
          DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedModel.GetType());
          deserializedModel = ser.ReadObject(ms) as T;
          ms.Close();
          return deserializedModel;
      }
  }

Open in new window

 
 The problem is calling the generic method on line 49 in this unit test: 'SuperHero' is a type, which is not valid in the given context      
'SuperHero' is a type, which is not valid in the given context
Here's the test class:
    [TestClass]
    public class DeserializedJsonToModelTest
    {
        private SuperHero hero;
        private DeserializedJsonToModel deserializer;

        [TestInitialize]
        public void Setup()
        {
            hero = new SuperHero()
            {
                FirstName = "Barry",
                LastName = "Allen",
                HeroName =

Open in new window

0
Starting with Angular 5
LVL 12
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

Hello Experts,
I have a Forget Password link in the Login Page.  When clicked, I received an email with a link to Reset the password.  In email, it contains a link, which will take you to the page where you can reset it. The problem is when I click on the link, the page error ed out with the following error message.  Any idea what is going on.  Any idea how to debug the page when loaded directly from the link?  Please let me know if you can.  Thank you in advance.

Thank You!

Server Error in '/' Application.

Object reference not set to an instance of an object.
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

 Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:
0
I've tried, Directory.Exist. I have tried some P/Invoke Marshalling from Win32 API Functions. They all seems to work, but the issue here is when i come across a share that doesn't exist it can take as long as 120 seconds to get a response back. I minimized the amount of times I perform the check by only running the check if the remote server exists, if it doesn't then we know the share doesn't exist.

Currently I am utilizing this piece of code to check if a share exists. What this does in essence is only allow the thread to run for 10 seconds and force an abort, but the abort may not work forcing the thread to run until the function finishes. The issue i have with that is since after 10 seconds I exit the code and unblock the calling thread but i never get the true result of the function since i am no longer waiting for it, which in some cases shows that the share exists but but with a weird error such as Error 1396 for example.

I have about 3,000 of these shares to check so if I didn't use a timed thread the checks could potentially take forever to complete.

Does anyone have any ideas on how to make this faster, whether its a different check function or how i go about using the thread logic?

Thanks

protected static void CheckResource(String strLink, ref String shareStatus)
    {
        String shareStatus1 = "NOT ACTIVE";

        Thread t = new Thread(new ThreadStart(delegate () {
            IntPtr pZero = IntPtr.Zero;
            IntPtr pSid = pZero;

Open in new window

0
I need to get the selected value of a listview that has 2 columns. I think this should be simple, but I am not getting the value I need. I have a winforms application, in C#. I populate the list view like this:
foreach (var item in documents)
{
	lstMyList.Items.Add(item.Name + "\t\t" + item.Value + "\t\t");
}

Open in new window

It displays the list with the values side by side. When I select a value from the list, I want to capture just the item.Name value. How can I do that?
0
Hi Experts,
I am working on a MVC.Net application with C#.Net code-behind.

I am using an Array in one of my views.
I am able to populate my array just fine, but I need to do the following once I have populated my array:
1. Group by the following fields: order, item, description
2. Sort by the following fields: order, item, description

I have included my javascript code below.  
Please show me how to do my grouping and sorting of my javascript array.

var claimsHeader = new Array(); 



function onDataBoundHeader(arg) {
	var dataItemsHeader = arg.sender.dataSource.view();

        for (var j = 0; j < dataItemsHeader.length; j++) {
            var order = dataItemsHeader[j].get("Item");
            var item = dataItemsHeader[j].get("Market");
            var description = dataItemsHeader[j].get("Description");
            
            var claims = new Array(order, item, description);
            claimsHeader.push(claims);
        }
}

Open in new window


Thank you in advance,
mrotor
0
For a stored query (name is "CREAT_Plot") like the following in Access, what would be the vb.net or C# code to call this query and also pass a parameter in place of "[Reports]![TestReport]![Subject]"

SELECT CREAT.Subject, CREAT.CREAT, (IIf([CREAT.TargetDays]=".",".",Val([CREAT.TargetDays])*24)) AS TargetDays
FROM CREAT
WHERE (((CREAT.Subject)=([Reports]![TestReport]![Subject])))
ORDER BY CREAT.TargetDays;

I have googled about this but could not find an example to call stored query that prompts for input parameters.
Please kindly give me small code snippet to achieve this one.

Thank you
0
I am trying to query/get the value of a node from an xml which has namesopaces.
However I always get "Object reference not set to an instance of an object."

Here is the xml that I am using -

xml.png
I am using the following code to retreive the value of the node, as marked in the xml -

 string xmlResponse = "<?xml version=\"1.0\" encoding=\"utf-8\"?><feed xml:base=\"https://abcd.com/_api/\" xmlns=\"http://www.w3.org/2005/Atom\" xmlns:d=\"http://schemas.microsoft.com/ado/2007/08/dataservices\" xmlns:m=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\" xmlns:georss=\"http://www.georss.org/georss\" xmlns:gml=\"http://www.opengis.net/gml\"><id>asd-123-qwe-456-zxc</id><title /><updated>2018-09-18T12:18:54Z</updated><entry><id>https://abcd.com/_api/SP.WebParts.WebPartDefinitionasd-123-qwe-456-zxc</id><category term=\"SP.WebParts.WebPartDefinition\" scheme=\"http://schemas.microsoft.com/ado/2007/08/dataservices/scheme\" /><link rel=\"edit\" href=\"SP.WebParts.WebPartDefinitionasd-123-qwe-456-zxc\" /><link rel=\"http://schemas.microsoft.com/ado/2007/08/dataservices/related/WebPart\" type=\"application/atom+xml;type=entry\" title=\"WebPart\" href=\"SP.WebParts.WebPartDefinitionasd-123-qwe-456-zxc/WebPart\"><m:inline><entry><id>https://abcd.com/_api/SP.WebParts.WebPartDefinitionasd-123-qwe-456-zxc/WebPart</id><category term=\"SP.WebParts.WebPart\" scheme=\"http://schemas.microsoft.com/ado/2007/08/dataservices/scheme\" /><link 

Open in new window

0
Hi,
I am using Renci.SshNet to upload the files over SFTP. Below is my code.

var connectionInfo = new ConnectionInfo(host,
                                    objFI.UserId,
                                    new PasswordAuthenticationMethod(objFI.UserId, objFI.Password),
                                    new PrivateKeyAuthenticationMethod("rsa.key"));
 try
                    {
                        using (SftpClient sftp = new SftpClient(connectionInfo))
                        {
                            try
                            { 
                                    sftp.Connect();
                                    if (sftp.IsConnected)
                                    {
                                        using (var file = File.OpenRead(FilewithUploadingext))
                                        {
                                            if (file != null)
                                            {
                                                sftp.BufferSize = 4 * 1024; // bypass Payload error large files                                                     
                                                sftp.UploadFile(file, Path.GetFileName(FilewithUploadingext), (uploadCallback) =>
                                                {
                                                    ServerFileSize = uploadCallback;
                                                });
                                            }
              

Open in new window

0
Hello Experts,
I have a Onclick event attached to button which should open a window (on Javascript), which is working just fine.  But, when I click on another URL same window opens up, which is not related to the URL at all.  Any idea what could be going on?  Please try to help.  Thank you in advance.

Note:  Due to company's restrictions I will not be able to post the code here.

Thank you!
0
I need a help sample code to connect to ZenDesk API using basic authentication, User Email and Token written in C#. Please advise.
0
Become a Microsoft Certified Solutions Expert
LVL 12
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

Using c# .NET Winforms, I'm creating a few Panels programmatically with Checkboxes and buttons inside every Panel.
With a TextBox I need to create a filter filtering Panels by Name with the text of a TextBox and sorting the result

Something like: if textbox1.text contains "stringX" then only show Panels Name that contais "stringX" and order that Panels.

How Can I do that?


        private void Form1_Load(object sender, EventArgs e)
        {

        }
        static string[] ContainersList()
        {
            string[] containers = new string[6];
            containers[0] = "CodeJavaProcess";
            containers[1] = "ApiJavaProcess";
            containers[2] = "wsJavaProcess";
            containers[3] = "FrontJavaProcess";
            containers[4] = "BackJava1";
            containers[5] = "BackJava2";
            return containers;
        }
        
        int A = 1;
        private void button1_Click(object sender, EventArgs e)
        {

            var p = ContainersList();
            foreach (string o in p)
            {

                Panel ControlContainer = new Panel();
                ControlContainer.Name = "" + o;
                ControlContainer.Left = 10;
                ControlContainer.Top = A * 25;
                ControlContainer.Width = 600;
                ControlContainer.Height = 25;

                //Button Start Container
                Button btStart = new Button();
                btStart.Name = "Start" + 

Open in new window

0
Dear Experts,

 I have a desktop C# exe application, fail with the following exception:

System.Net.WebException: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.
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.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   --- End of inner exception stack trace ---


The application updating Salesforce by webservice

can you please help

Thanks
0
I need to know a few things about the following:

Microsoft Visual C++ 2013 Runtime Package for Windows

- filename of the DLL
- Is it available as a NuGet Package?
- If this is missing, how do I include it in my C# mobile app?
-  If I installed the Windows 8.1 SDK - what would be the path to this file?

Thank you!

Tom
0
I have a ASP.Net MVC 5 C# application that uses JWT tokens to GET (request) a token to get access to the database. The issues that I am running into are the c# code for on the IdentityConfig.cs ApplicationUserManger I set the login lockout defaults. Those defaults do not work. I have a MaxFailedAccessAttempts set to 3 when I login with the incorrect password more than 3 times the account does not lockout the user. The user should be locked for 5 minuets (which I don't know if that works because the lockout code is not working). To generate an email which the users gets in their email inbox than click on a link on the email and then takes the user to the password reset page where the password is suppose to be reset by getting a JWT token to GET then PUT the change to update the database table with the new password.
0
I have the following code on .aspx page
<div style="text-align: center; float: left;">

                            <input type="radio" name="rbauthorship" value="First Author" runat="server" class="required" />
                            First Author
                            <input type="radio" name="rbauthorship" value="Corresponding Author" runat="server" class="required" />Corresponding Author
                            <input type="radio" name="rbauthorship" value="Co Author" runat="server" class="required" />
                            Co Author
                        </div>

On C# code behind, I am returning dataset which contains  authorship values. I want Based on value returned the corresponding radiobutton should get checked.
string a=dt.Rows[0][0].ToString();
if(a=="First Author")
{
     //What to write here so that first radio button gets checked

}
0
Please help with writing a query to get aggregated OrderAmount for each SalesPerson for the last month (last 28-31 days). For example, if today is 09/13/2018, we need sum from 08/13/2018 to 09/12/2018.

TableOrders
----------------
SalesPerson
OrderAmount
OrderDate


Thank you in advance.
0
I developed software recently for a company where the software I developed is using C# to write to/read from a database attached to a SQL Server Express instance installed on the local machine while the customer is connecting to that instance as a linked server to push/pull information to and from it.  

Well, it seems that after the customer pushed some data to the SQL Server Express instance database while the software was open and connected, I was no longer able to access the data correctly until I close the software down and restarted it (thereby closing the connection and re-opening it).  

I don't know the exact sequence of steps preceding this event and this was the first connection to the local sql server database through the linked server and there had been no issues prior.  So, is there anything that anyone can think of that would disrupt a connection this way?  Anything that might be missing in my connection string, for example?  

Thanks.
0
I am trying to create a method which can retrieve JSON objects.  I’m using the Jama API (https://dev.jamasoftware.com/rest)
To simplify it I am using RestSharp
I start by using the Jama swagger tool to test the interface.  This produces a Response Body.  I take this response body and in visual studio create a new class using the paste special ‘paste JSON as classes’ command.

This results in a new class:

public class Item
    {

        public class Rootobject
        {
            public Meta meta { get; set; }
            public Links links { get; set; }
            public Datum[] data { get; set; }

            public static explicit operator Rootobject(List<object> v)
            {
                throw new NotImplementedException();
            }
        }

        public class Meta
        {
            public string status { get; set; }
            public DateTime timestamp { get; set; }
            public Pageinfo pageInfo { get; set; }
        }

        public class Pageinfo
        {
            public int startIndex { get; set; }
            public int resultCount { get; set; }
            public int totalResults { get; set; }
        }

        public class Links
        {
            public DataFieldsLookup5 datafieldslookup5 { get; set; }
            public DataLockLockedby datalocklockedBy { get; set; }
            public DataFieldsLookup6 datafieldslookup6 { get; set; }
            public DataFieldsLookup3 datafieldslookup3 { get; set; }
        

Open in new window

0
Using the example found here: https://stackoverflow.com/questions/547172/pass-through-mouse-events-to-parent-control
I was able to create a Panel control that passes all mouse activity to the underlying control(s). The trouble for me is that it passes ALL mouse activity. I need something that will intercept mouse move behavior but will still allow click events (left click, right click, mouse down, mouse up, and double click) to pass through. Does anyone know how to modify this code to accomplish that task?
0
JavaScript Best Practices
LVL 12
JavaScript Best Practices

Save hours in development time and avoid common mistakes by learning the best practices to use for JavaScript.

I running into a pittfall I have an action that I'm trying to refactor so that it call a service that will populate a model that I created.

 My only issue is that I have a bunch of method that I'm not sure if they should belong to the service or I just should leave them on the controller level. My assumption is to not implement these method in my new service that I will create.  The methods that I'm referring to are as follow:
 PopulateSecurityParameters(parameters, viewModel);
  PopulateCancelSoldParameters(parameters, viewModel);
  PopulateCallLogParameters(parameters, viewModel);

[  private ViewModel GetViewModel(Employee employee)
        {
            var viewModel = new ViewModel();
            var parameters = ParameterConfigurationService.GetParameters();

            viewModel.CommonSmtpSettingsOptions = GetCommonSmtpSettingsOptions();

            viewModel.StatusInfoList = GetStatusInfoList(parameters);

            PopulateSecurityParameters(parameters, viewModel);
            PopulateCancelSoldParameters(parameters, viewModel);
            PopulateCallLogParameters(parameters, viewModel);
            PopulateGeneralParameters(parameters, viewModel);
            PopulateAppointmentCallParameters(parameters, viewModel);
            PopulateSmtpParameters(viewModel);

            viewModel.CountryOptions = GetViewModelCountryOptions(viewModel.SelectedCountry);
            viewModel.QuickNoteOptions = 

Open in new window

0
I have a silverlight app hosted on windows 7 and IIS, it works fine

I'm trying to move to a different box (windows 10) and its not working
I've run fiddler tool and can see the SVC binary requests are not found (404)
As this is a direct copy of the published code, I assume its setup related
If i run the project through visual studio it works fine, but in IIS does not

Here is an example of the url that isn't found on the new box:
http://localhost/MasterUI/ClientBin/MasterUI-Web-GuiViews.svc/binary/GetV_gui_TempAlarmGraph_by_Site?site=0001&ent=FFFFFFFF
The above gives a 404 in fiddler

The previous request to the XAP file works and does NOT 404
http://localhost/MasterUI/ClientBin/MasterUI.xap

I've tried to duplicate the IIS setup as much as possible, but for some reason it isn't working

My solution consists of 2 projects
MasterUI (silverlight stuff here)
MasterUI.Web (this is the non silverlight app - .aspx files)


The windows 10 box is a fresh install, so perhaps i'm missing some components, but as its working in visual studio on this windows 10 box, I assume it's IIS setup related?
0
How to implement role-based security? There are pages that only few people are allowed to see and edit.
Is there any C# example of this?
0
Adding configuration manager in namespace so it can be visible to all the classes is not possible as below

Public string cs = ConfigurationManager.ConnectionStrings["ProductCalls"].ConnectionString; >>>>>> This does not work.

It seems that it works only if code is place inside each Public classes.


Namespace ABC



{
    Public Class XYX
{
 ,,,,,,,,}

Public Class XXX
 {
    }

Public Class ZZZ
{

   }
0
I am trying to upload multiple files. Everything seems to be working just fine but my controller is saying that the request failed. What am I doing wrong?

$(document).ready(function () {
    $('#RequestDetailFiles').on('click', function () {
        var data = new FormData();

        var files = $("#DetailFileUpload").get(0).files;

        // Add the uploaded image content to the form data collection
        if (files.length > 0) {
            for (i = 0; i < files.length; i++) {
                data.append("UploadedImage_" + i, files[i]);
            }
        }

        $('#DetailAppended').empty();
        $('#RequestDetailUploaded').empty();
        $("#RequestDetailUploaded").append('<p>Uploaded Files</p>');
        $("#RequestDetailUploaded").append('<ul id="DetailAppended">');
        for (var i = 0; i < files.length; i++)
            $("#DetailAppended").append('<li>' + files[i].name + '</li>');

        //append other form data.
        var requestId = $("#RequestId").val();
        data.append("Type", "Request Details");
        data.append("TypeId", "1");
        data.append("RequestId", requestId);

        // Make Ajax request with the contentType = false, and procesDate = false
        var ajaxRequest = $.ajax({
            type: "POST",
            url: "/uploadfile/uploadfile",
            contentType: false,
            processData: false,
            data: data,
            success: function (data) {
                //data is your result from 

Open in new window

0
After successfully inserting a record using the try,,catch.., I 'd like to use a bootstrap call to display the message as shown below.
     try
                {
                    // Do something
                    AppThis.InsertUpdateProduct();
             
            // I'd like to display the message calling a bootstrap alert  saying "Successfully added!"
                     
                }
                catch (Exception ex)
                {
                    // Log 
                    string strErrNum = ex.Message.ToString();

                    // Display message to users

                }

Open in new window

0

C#

93K

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