C#

94K

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've integrated into a 3rd party java windows app which is forwarding messages via http post and get
They call it forwardURL, and its running locally so just hits http://127.0.0.1/etc

On the other side of this I have  multithreaded c# 4.6 console app which accepts the forwarded messages and saves them
I've noticed recently I've started to miss messages, and in one instance, there were 14 mins of messages missing

I'm trying to figure out the issue with logging etc, but wondered if there is a technology limit/server configuration limit (win 2016)
when I get to 30 messages a second, I've noticed messages start going missing.

Is there a limit that i'm unaware of, or some setting in the console app/windows that needs checking that might be responsible for these missing messages?
0
In c#, For Example the list contains {Eid:67,EName:'dyt',DOB:06/09/2017,Sal:6078}.
Actually i declared a class with properties as Eid,Ename,DOB,Sal etc...
 my question is from list i need to retrieve values and need to assign it to specific property.
For ex: Eid property need to assign 67.
like that for all properties in c#.

could you please help
0
I want to create setup file (EXE) for c# windows application with using database of SQLite.
0
Hi ,
For one of my client their AD structure is like
Domain architecture example :

•      xyz.com (Main Domain)
1.      abc.xyz.com (Subdomain)
      abc.xyz/User1  --> user in abc sub domain
      abc.xyz/User2  -->user in abc sub domain
      ADGrp1  --> Ad group in this abc domain
      ADGrp2  --> Ad group in this abc domain


2.      test.xyz.com (Subdomain)
    test.xyz/User3    --> user in test sub domain
   test.xyz/User4    --> user in test sub domain
    ADGrp3  --> Ad group in this test domain
    ADGrp4  --> Ad group in this test domain

Now problem arises when in my web.config ADGrop3 is configured and and ADGrp3 consist od cross sub domain abc.xyz\user1 and user is not getting acces.

 private List<string> GetGroups()
        {
                  List<string> groups = new List<string>();
                  if (string.IsNullOrEmpty(domainName)) return groups;
           
            using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domainName))
            {
                try
                {
                    UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, userName);
                    if (user != null)
                    {
                        PrincipalSearchResult<Principal> groupResults = user.GetGroups(principalContext);
                                    groups = getItems(groupResults);
                    }
                }
                catch (Exception ex)
                {
                    string errorMessage = "AD …
0
I am writing unit test cases using xunit, moq and c# in visual studio core. my methods get results from database and returns employee object. I would like to write unit test cases without hitting DB. Please find attached class and interfaces.
Employee_Entity.txt
EmployeeBusinessLayer.txt
EmployeeRepository.txt
0
First I am doing the uninstallation of custom window service by this code...


During execution of this code may be some threads running internally....

After that I am running another .exe by this code but code of this .exe is running then sudden degug goes to another line.I have identified and remove the "custom window service" code and check it is running fine.May "custom window service" code did not close the internal thread .
0
Guide me how to create (deploy) exe file of  windows application in c#  with database of mysql ??
0
I'm trying to debug an error in our C# Entity Framework code and would like some help trying to isolate the problem.

The code appears quite simple - it is updating a row in a table.

There exists a component test which runs this same code and it works.

However run from within ASP.NET the SaveChangesAsync() call just has a weird failure where no exception is thrown but the stack is cleared.
Let me just break that down a little:
The method that saves the changes works, but it is called using "await" and when I step through the debugger I never return to the original code that made the call. Similarly if I set a breakpoint it never hits any of the code after the await call.

If I then try to run a SELECT on the row the update was run on, I get a lock. When I reset IIS the transaction must rollback because the update isn't performed.

Things are complicated somewhat because the codebase I am using has various layers on top of the standard EF code which makes it difficult to share the code, however it looks like it is just using the following settings for the transaction

TransactionScopeOption.Required
TransactionScopeAsyncFlowOption.Enabled
IsolationLevel Serializable
Timeout 00:00:00

What could I do to try to isolate the cause of the problem?

I'm using Entity Framework 6.1.1
0
I have a database column that I am trying to get the sum for every record. In my test sample I am only returning 6 records

My column is called WageAmount. I have tried everything and my decimal shows a value of 0. The statement returns no row with a null value.

convert(decimal(18,2),Sum(PR.WAGE_AMOUNT end)) AS [WageAmount],

In c# my code is
 decimal d = 0;
                decimal total = dt.AsEnumerable().Where(r => !r.IsNull("WageAmount") && decimal.TryParse(r["WageAmount"].ToString(), out d)).Sum(r => d);

d = 0 and total = 0. What am I doing wrong?
0
Hi
for an interface we have to create an xml file. We use XmlDocument.

We need to create an element that contains the plain text  &#13;&#10;
<RecordDelimiter>&#13;&#10;</RecordDelimiter>

The problem is that c# always writes a real "CarrigeReturn Linefeed"  chr(13)chr(10)  instead.
0
Not sure why i am getting this error -

Operand type clash: varchar is incompatible

I am using User Defined Table type  in stored procedure .and calling using C#.
0
am writing unit test cases for my validation class  to check valid integer or string using fluentvalidation. In my class, ValidationCheck.cs  there are two methods. Attached file for your reference.  These methods have two arguments  one is  value and 2nd parameter is CustomContext which contains name of the property(EmpID or EmpName) etc. I am having difficulties to write unit test case for these two methods in xunit/nunit and c# in visual studio.  Below my test class.

 public class ValidationChecksTest
    {
        [Fact]
       public void IntCheck()
        {
            ValidationChecks validationChecks = new ValidationChecks();

            CustomContext customContext = new CustomContext(); // CustomContext constructor expecting to pass PropertyValidatorContext context as parameter.  I am having difficulties here how to get CustomContext object and pass to IntCheck method. Basically the customContext object will have name of the property etc. 
            validationChecks.IntCheck(10, customContext );   
        }
    }

Open in new window


Please let me know if you need any further details. appreciate your quick help. Thanks.
ValidationCheck.txt
0
Hello,
I am having a tree dynamically created on the left side of window form. Is there anyway i can iterate the tree and get the count of child nodes and store the count to use it?

Thanks.
0
I have an aspx page with some input controls , along with an user control  ( see sample below).
I have some input in default.aspx page and some more in ascx page.

when I submit the form in default aspx page, I want to read the input values in that user entered in ascx page as well and save those along with the form values in the aspx page.
how can i save the input values from both default.aspx page and ascx control, all at once  ?

Default.aspx page ---

<%@ Register Src="~/WebUser.ascx" TagPrefix="uc1" TagName="WebUser" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
   
    <div class="row">
        <div class="col-md-6">
            <label>default text box</label>
             <asp:TextBox ID="txtusername" runat="server" ></asp:TextBox>
        </div>
      <div class="col-md-6">
          <uc1:WebUser runat="server" id="WebUser" />
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <asp:Button ID="savbtn" runat="server" text="save" OnClick="savbtn_Click"/>
        </div>
    </div>
</asp:Content>

WebUser.ascx page

<asp:textbox id="useremail" runat="server>
0
I want to delete files that have a certain criteria in the filename.

I have the below code which works with deleting directories.
        public const string Excel = "*.xls*";

        public static string GetFilesWithExt()
        {
            return Excel;
        }

        public const string CAD = "CAD";

        public static IEnumerable<string> RemoveDirectories = new[]
        {
            CAD
        };

        List<string> files = Directory.GetFiles(dir, CriteriaConstants.GetFilesWithExt(), SearchOption.AllDirectories)
                                          .Where(dirs => !CriteriaConstants.RemoveDirectories.Any(dirname => dirs.Contains(dirname))).ToList();

Open in new window

I tried the below code but I do not get any data.
        public const string Excel = "*.xls*";

        public static string GetFilesWithExt()
        {
            return Excel;
        }

        public const string BOM = "BOM ";
        public const string TopLevel = "Top Level";

        public static IEnumerable<string> RemoveFiles = new[]
        {
            BOM,
            TopLevel
        };

        List<string> file = Directory.GetFiles(dir, CriteriaConstants.GetFilesWithExt(), SearchOption.TopDirectoryOnly)
                                .Where(dirs => !CriteriaConstants.RemoveFiles.Any(dirname => dirs.Contains(dirname))).ToList();

Open in new window


Found the issue.  I'm using Directory.GetFiles to obtain a list of files.  The directory contains the name "BOM" and the filename also contains the name "BOM".  How do I delete where the filename contains "BOM" regardless of the directory.
0
Actually i have a requirement like for example I have a login page and i have logged in,

now while clicking logout button  i have to do some database updation and suddenly without clicking the logout button if the user

closes the window no updation will take place.

How to detect the browser close event in ASP.Net (C#) . aspx.cs file
0
I cannot get HttpContext to work in ASP.NET Core.


 public string GetCartId()
        {
            if (HttpContext.Current.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrWhiteSpace(HttpContext.Current.User.Identity.Name))
                {
                    HttpContext.Current.Session[CartSessionKey] = HttpContext.Current.User.Identity.Name;
                }
                else
                {
                    // Generate a new random GUID using System.Guid class.     
                    Guid tempCartId = Guid.NewGuid();
                    HttpContext.Current.Session[CartSessionKey] = tempCartId.ToString();
                }
            }
            return HttpContext.Current.Session[CartSessionKey].ToString();
        }

Open in new window

 Visual Studio keeps coming back with red squiggly lines under the words HttpContext and the Error message "The name 'HttpContext' does not exist in the current context."

As a bit of background, I'm making two big leaps at once: (a) trying ASP.NET Core for the first time and (b) trying to use C# for the first time after years of just VB/asp.net.  I like a challenge!  To help get me there, I'm using a few online guides:
Getting Started with EF Core on ASP.NET Core with an Existing Database
and
ASP.NET Shopping Cart

In effect, I've followed the first link through from starting a blank project to setting up database CRUD pages and tested - all good.  However, when I insert the shopping basket page from the second link, it errors on anything HttpContext related.

In an attempt to fix this, I've followed the suggestions on  ASP.Net Core Session State, added the relevant code hightighted in yellow for the startup.cs page - but to no avail.
0
I have a C# interface exposed to C++ via COM (tlb file),In this interface function i want to send array of  a Object s Object .Class of this object is complex and have different datatypes.I am using Connection pointer for call backs. Now my point is how can i use Safearrays to transfer data from C++ to C# UI.
0
This is in Windows Form Application where here Iam adding items to the combo box and in front end it is adding items as expected. But while retrieving items through selected item,selected index iam getting as blank values. could you please any one help  


protected override void OnLoad(EventArgs e)
        {
            State objState = new State();
            List<State> states = new List<State>();
            states.Add(new State() { Id = "1", Name = "Delhi" });
            states.Add(new State() { Id = "2", Name = "Jarkand" });
            states.Add(new State() { Id = "3", Name = "Orissa" });
            comboBox1.DataSource=new BindingSource(states,null);
            comboBox1.DisplayMember = "Name";
            comboBox1.ValueMember = "Id";
        }
        public object SelectedItems
        {
            get { return comboBox1.SelectedItem.ToString(); }
        }
0
I have a SVG file in XML format i am trying to deserialize XML to C# objects but when trying to deserialize XML data it is giving error

Below is my code

XmlSerializer serializer = new XmlSerializer(typeof(List<rootobject>));
object objectList = null;
using (StreamReader stream = new StreamReader(@"C:\Users\sana-user\Documents\Visual Studio 
      2015\Projects\SVGXMLToJsonApp\SVGXMLToJsonApp\File\3rect.svg"))
{
      objectList = serializer.Deserialize(stream);
}
 Console.WriteLine(objectList);

Open in new window


Below is my class

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.w3.org/2000/svg")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.w3.org/2000/svg", IsNullable = false)]
public partial class svg
{

    private svgStyle styleField;

    private svgG[] gField;

    private string[] textField;

    private decimal versionField;

    private string idField;

    private string xField;

    private string yField;

    private string viewBoxField;

    private string style1Field;

    private string spaceField;

    public svgStyle style
    {
        get
        {
            return this.styleField;
        }
        set
        {
            this.styleField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute("g")]
    public svgG[] g
    {
        get
        {
            return this.gField;
        }
        set
        {
            this.gField = value;
        }
    }

 

Open in new window

0
Input in Textbox is taken as string.
If the string contains H_2O, 2 should be displayed as subscript.
If the string cotains H^2O, 2 should be displayed as superscript.
0
I'm developing a web application to to fetch data from 'https://api.ebay.com/sell/analytics/v1/traffic_report'

I've a ebay developer account with ClientId: MyClientId ClientSecret: MyClientSecret AppId: MyAppId

To achive this, I need a OAuth token

To get OAuth Token I do the following steps.

I browse the url bellow

https://signin.ebay.com/authorize?client_id=MyClientId&redirect_uri=RuName&response_type=code&state=analytics&scope=https%3A%2F%2Fapi.ebay.com%2Foauth%2Fapi_scope%2Fsell.analytics.readonly

It goes to

https://signin.ebay.com/ws/eBayISAPI.dll?VAppJanessa&reqinput=reqinput - auto generate

after sign in it redirects to 'Grant application access to MySiteDisplayName' page.

After I Agree it redirects to 'https://my_site.com/?state=analytics&code=code' I've preapared a post request after collecting the code

I've executed the post request using POSTMAN like bellow

Post URL: 'https://api.ebay.com/identity/v1/oauth2/token'

Headers:

cache-control: no-cache

Content-Type: application/x-www-form-urlencoded

Authorization: Basic Base64 value of 'MyClientId:MyClientSecret'

Body:

grant_type: authorization_code

redirect_uri: RuName

code: code returned from previous request

After post request I've got the result

{ "error": "invalid_grant", "error_description": "the provided authorization grant code is invalid or was issued to another client" }

Please tell me what is missing or wrong.
0
Hello Experts,

Here is my issue. We (the company I work for)  have a bunch (20+) c# assemblies that we have made. For our customer to use these assemblies, they have to add each one as a reference and them and then add something like this to their .cs file:

using AssemblyOne;
using AssemblyTwo;
etc

My management wants me to combine the 20+ assemblies into one large assembly so that the customer can do something like this:

using OneHugheAssmbly;

I've been playing with ILMerge and it appears that I can merge them into one assembly, but that it still requires that the customer have:
using AssemblyOne;
using AssemblyTwo;
etc

Is there any way to combine them into one large assembly and also just us one "using" line?
0
I'm getting the following error from above. This is happening when I'm trying to send an external email to my own environment. The only issue I have looked all over online and I have set my parameters correctly as bellow.

 MyServer.UseDefaultCredentials = false;
 port is 587.
 network host="smtp.gmail.com
 enableSsl="true"

The error is ocurring in my following catch statement. Not sure what i'm missing or how could I write this catch statement more effectively.
    catch (Exception ex)
            {
                System.Diagnostics.Debug.Print(ex.Message);

                myReturn = 0;
                throw;   // this is where the error is occurring...

            }
            finally
            {
                MyMessage.Dispose();
                MyServer.Dispose();
            }


public static int SendEmail(company.Models.Email passEmail, string fromEmail)
        {
            int myReturn = 0;

            // Get SMTP properties for specific employee
            SmtpSettings mySmtpSettings = ServiceAssistantService.SmtpSettingsService.GetSmtpSettings(passEmail.Employee.ID);
            if ((mySmtpSettings == null || string.IsNullOrWhiteSpace(mySmtpSettings.UserID) || string.IsNullOrWhiteSpace(mySmtpSettings.Password) || string.IsNullOrWhiteSpace(mySmtpSettings.Server) || mySmtpSettings.Port == 0)
                && passEmail.EmailSettings != null)
                mySmtpSettings = passEmail.EmailSettings;

            

Open in new window

0
Hi, I have a scanned pdf file which and I'd like to find the position (in coordinates) of a black square at the top of a page.
 I've used iTextSharp but  I cant get to find anything, even text, as the whole page is an image.

Is there a way to achieve this?? Would it be easier if the pdf page was converted to a jpg for example?

square.PNG
0

C#

94K

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