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

Dear Experts:
I would like to set a date parameter default date value to today at 6AM.
e.g. 7/01/2018 6:00:00 AM
In other words I need the expression that can replace this expression that is not working:
=CDate(Format(Now(), "dd/MM/yyyy") + " 6 AM")


Note: I use SSRS 2016 and. I tried to run this report through the web service and fails with the invalid date error.
If I use expression =Today() then it works without any issue.
0
Free Tool: IP Lookup
LVL 11
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

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

Hi,

I am trying to run a query in code behind, because the query is simple, I do not want to create a sp just for that. Here is my code. It runs well without a parameter.


        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["conn"].ToString());

        SqlCommand cmd = new SqlCommand("SELECT CategoryName from Category ORDER BY CategoryName="  + Session["sCMID"], con);

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable table = new DataTable();
        da.Fill(table);

        ContactName.DataSource = table;
        ContactName.DataValueField = "CategoryName";
        ContactName.DataTextField = "CategoryName";
        ContactName.DataBind();


        con.Close();

Open in new window


The result will be loaded into a dropdown list.  thAnks
0
Can someone tell me where is the ASP.NET Core Web Application template?
It's there for C# but is missing for VB.NET
1
Hi All

I am clearly missing something here. I am trying to send calls to an API for a product called ServiceDeskPlus.

The operation name "ADD_REQUEST"  should be sent as a "POST attribute" with key "OPERATION_NAME".

The technician key should be sent as a "POST attribute" with key "TECHNICIAN_KEY".

Input is an XML string sent as a "POST attribute" with key "INPUT_DATA".

The full documentation page is found here.

The code I am using to create the Post Attributes is:
public void CreateSupportDeskItem(ref SupportItem supportItem, string clientCode = "")
        {
            string destinationUrl = Properties.Settings.Default.ServiceDeskEndPoint;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);

            string group = Properties.Settings.Default.ServiceDeskGroup;
            string status = Properties.Settings.Default.ServiceDeskStatus;
            string service = Properties.Settings.Default.ServiceDeskService;
            string technicianKey = Properties.Settings.Default.ServiceDeskAPIKey;

            string requestXml;

            if (string.IsNullOrEmpty(clientCode))
                requestXml = GenerateRequestXml(supportItem,
                                         group, status, service);
            else
                requestXml = GenerateRequestXml(supportItem, group, status, service, clientCode);

    

Open in new window

0
I am writing code to send an email via SMTP.  Which design pattern should be used to implement.  High level example would be nice.

Thanks
0
Hi,
I am using GridView in C#

<asp:LinkButton ID="LinkButton5" CommandArgument='<%# Eval("EmailAddress") %>' CommandName="LinkEmail" runat="server" Visible="true" HeaderStyle-Width="10%"><%#Eval("EmailAddress")%></asp:LinkButton>

Open in new window


I am trying to pass email to a javascript
   protected void recordListContact_RowCommand(object sender, GridViewCommandEventArgs e)
    {


        if (e.CommandName == "LinkEmail")
        {
            string EmailAddress = e.CommandArgument.ToString();

            ScriptManager.RegisterStartupScript(this, GetType(), "myFunction", "SendEmail(" + EmailAddress + ");", true);
            

        }

    }

Open in new window


But the string always returns empty, it works when passing the int. Any ideas? thanks
0
Hi I have a typed datatable filled from sql server, bound to 2 gridviews
I need to loop through each row every 5 mins and check if price has changed, if so update it. (the price is coming from an external server)

I did have this on a timer and then loop through each row on same thread but was freezing the UI well it was looping, so now have a background worker to check and update.

the only way i seem to be able to get it to work is to clone the table then loop through rows then on background work completed fill the table again. There must be another way.
If I dont clone the table first the ui freezes and does not recover. Please help.
0
The only difference between the two nearly identical methods is DoA() calls MyA() while DoB() calls MyB(); and the parameters for DoA and DoB differ in both type and number.
    private class DoA(string x)
    {
       ... identical code ...
           string result = MyA();
       ... more identical code ...
    }

    private class DoB(string x, int y)
    {
       ... identical code ...
           string result = MyB();
       ... more identical code ...
    }

Open in new window

How can I factor out all that identical code? The calls to MyA() and MyB() are inside a loop.
0
I am using Invoke-WebRequest in Powershell to authenticate against Forms authentication in a C# MVC site.

I have usually done it this way successfully;
$webServerUrl = 'http://localhost:54363'

$r = Invoke-WebRequest $webServerUrl -SessionVariable my_session
$form = $r.Forms[0]
$credentials = Get-Credential
$form.fields['Username'] = $credentials.GetNetworkCredential().UserName
$form.fields['Password'] = $credentials.GetNetworkCredential().Password
$form.fields['RembemberMe'] = $true;

$r = Invoke-WebRequest -Uri $($webServerUrl + $form.Action) -WebSession $my_session -Method GET -Body $form.Fields

Open in new window


As you can see, I retrieve a form, set username and password and log in.
But now in the recent version of the system, the first Invoke-WebRequest fails and the $r variable is never populated.

I get the html of the page outputted to the Powershell terminal window and at the end of that I receive:
+ $r = Invoke-WebRequest $webServerUrl -SessionVariable my_session
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebExc
   eption
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Open in new window


I have tried debugging the MVC application while sending a request with Powershell, and I cannot see anything out of the ordinary. The LoginController and its Index method returns 401 Not Authorized with the HTML for a login form. When I use that form in a web browser, I can log in. But my attempt  in Powershell still fails.

The error variable displays this:
$error[0].Exception
The remote server returned an error: (401) Unauthorized.

Open in new window

0
I'm contemplating the design of classes, playing with a simple hypothetical design, and wondering if there's some general principle of good design this violates, and if there's a better way.

Say I have a class of Messages. Each message is a string. The Messages class holds a list of all the message strings.

I want to send these messages to their destination. Say, write them to a file. So I have a MessageSender class which does the job.

Class Diagram

using System;
using System.Collections.Generic;
using System.IO;

namespace TestMessages
{
    class Program
    {
        static void Main(string[] args)
        {
            var messages = new Messages();
            var messageSender = new MessageSender();
            messageSender.SendMessages();
        }
    }

    public class Messages
    {
        public static List<string> myMessages;
        public Messages()
        {
            myMessages = new List<String>(new string[] { "one", "two", "three" });
        }
    }

    class MessageSender
    {
        public void SendMessages()
        {
            using (StreamWriter writer = new StreamWriter("myFile.txt"))
            {
                foreach (string s in Messages.myMessages)
                {
                    writer.WriteLine(s);
                }
            }
        }
    }

}

Open in new window

This all works. But I see problems.

First there's the obvious static List in the Messages class, which makes it global and easily accessible, and abusable.

And the Messages class is just data with no behavior.

Second, I see MessageSender reaching in to class Messages and extracting the data. This is the one I'm not sure if it violates encapsulation, or some other good design principle.

I can make the MyMessages list not static:

Class Diagram

Open in new window

0
Free Tool: Port Scanner
LVL 11
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

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

I have some C# code which looks something like this:
using (StreamWriter output = new StreamWriter(filename)
{
    output.Write("<HTML>");
    output.Write("<HEAD>...</HEAD>");
    output.Write("<BODY>");
    output.Write("<TABLE>");
    output.Write( table header stuff);

    // Now we output the HTML Table rows of data
    foreach(MyData data in myDataList)
    {
        output.Write("<tr><td>" + data.column1 + "</td><td>" + data.column2 + "</td><td>" + data.column3 + "</td></tr>");
    }

    output.Write("</TABLE>");
    output.Write("</BODY>");
    output.Write("</HTML>");
}

Open in new window

My question is, is there a better way of doing this? Can I somehow create a template, which looks like an HTML file, something like:
template = 
<HTML>
  <HEAD>
    ...
  </HEAD>
  <BODY>
    <TABLE>
      <tr><th>Column 1</th><th>Column 2</th><th>Column 3</th></tr>
      {magically fill in rows here from data}
    </TABLE>
  </BODY>
</HTML>

Open in new window

This looks nice, all except how would I get my C# code to "magically fill in rows here from data"?
0
https://www.experts-exchange.com/questions/25136887/Hide-duplicate-field-values-in-a-GridView.html

anyone knows this in C# / .nets / .aspx?

I have an appointment table, one appointment slots consists of 2 groups.
Each group can only have a maximum no. of 10 people.
I want to show the appointment date, time and group number once,
and the names of the people in the group will be shown.

e.g.

Date    Time    Group       Name
------------------------------------------------
xx         xx          1                Katy
                                             John
                                             Sam

xx         xx           2               James
                                             Rick
                                             Mike
0
1. I have a page with some fields like first name, last name, address, city, etc.

2. Some fields are required and some aren't.

3. On the page, I want to have 2 buttons; "Save for later" and "Save & Submit"

4. I created two tables with the same fields. In one table (for Save-for-Later"), I have the fields as nullable.
     In the real table (table for Save & Submit), I have the required fields as non-nullable and the non-required ones as nullable.

So, I have 2 tables. I wonder if this is a good design. If I want to display ALL the data (complete and incomplete) in a table, I have to go to two tables and get the data. Maybe I need a "complete" flag?

Maybe I just need one Save-For-Later table and have all the fields as nullable. When user clicks on "Save & Submit".... I insert the row from one table to the other?

Any ideas or is my orig design idea is good?
0
I'm going to have a page that contains many gridview controls. I'm trying to create a custom sort method for my GridView controls. I have an organic example that works just fine in my code.

        protected void myGridViewControl_Sorting(object sender, GridViewSortEventArgs e)
        {
            //PSUEDO CODE NOT WRITTEN FOR CORRECTNESS
            DataSet myDataSet = new DataSet();
            myDataSet  = myGridViewControl.Sort(someData, e.SortExpression).ToList();
        }

Open in new window


...and this works fine. So I try to then, I add another grid view control and use that grid's OnSorting method to pass the GridView control to my custom method. In essence, passing my grid and its GridViewSortEventArgs to my new global sorting method:

        protected void dtgClinicScheduledEvents1_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortAllGrids(sender, e);
        }
.
.
.
        protected void SortAllGrids(object sender, GridViewSortEventArgs e)
        {
            GridView gridView = (GridView)sender;
            string strID = gridView.ID;

            myCustomCollection myLocalColletion= new
                               myCustomCollection().BinaryDeserialize(Session[mySessionVariable] as string);
            myLocalColletion.AccecptColletion = gridView.Sort(myLocalColletion.AccecptColletions, gridView.SortExpression).ToList();
            Session[mySessionVariable] = myLocalColletion.BinarySerialize();
        }

Open in new window



I'm getting a few errors in my custom sort method that I don't understand. If you can accept that the 1st line of code and the 3rd line of code (marked above with 1 and 3) are correct, then the compile time errors I'm getting are as follows:
  1. Now, my "myLocalColletion.AccecptColletions" object is telling me that the 1st parameter of the grid's sort method, needs to be a string? Why

2. My second parameter now is now expected to be a string. Why is it no longer a string, it was before in the "organic" Sorting method.

3. Lastly, the "." is error-ing out at compile time telling me that: "Operator "." cannot be applied to operand of type" void'". Again, this was not the case before, so why is it now?
0
I have a datatable that is loaded on my page....and I just need to insert a row so my user can input data and save. I cannot  seem to make this happen....

Here is the jquery table referenced in the view:  I would think I could reference that table since its already loaded on page but having no luck.  Please help.

The columns that are rendered with existing data are Entity, Role, Designate, Allocation

within the jquery grid I am dynamically pulling the data ...Entity would be autopopulated, Role would load a dropdown, designate would load a drop down, and allocation would be a input for decimal values.  Then there would be an save and cancel button


<div class="col-xs-12">
        <div class="row" style="margin-bottom:4px;">

            @BootstrapHelper.Panel("GenericGrid-panel", BootstrapPanelCssClass.Primary, @Model.HeaderTextLeft, "",
                        false, @Model.Icon, "GenericGrid-panel-body", "",
                        @<text>

                            <div id="contactEntity-crud-div" class="col-xs-12" style="float:left;display:block">
                                test
                                <div id="main-container-contactEntity" class="container-fluid">

                                    <table id='contactEntity-crud' class="display" style="width:100%;"><tbody></tbody></table>
                                </div>
                            </div>
                        </text>, "", "",@<text>  </text>)




        

Open in new window

0
Lets assume I have a javascript method called createrow(dt, table)

I would like to call that when a user selects an item in my jquery autocomplete.

Ultimately what I need to do  is actually create a row in my jquery datatable when this happens..but I will make this function call do that  ....

Can someone help me with wiring this up..assuming the  method createrow(dt,table)

Here is my autocomplete code in my view in the scrips section

 $(".caAutoComplete_EntityEntityNameSearch").autocomplete(
        {
            source: "@Url.Content("~/Shared.mvc/EntityEntityNameSearchAuto")",
            minLength: 3,
            select: function (event, ui) {
                var inputlabel = ui.item.label;
                var inputvalue = ui.item.value;
                $("#hdnClientId").val(inputlabel);

             return false;
            }
        });

Open in new window


Here is where I use it in html:

<div id="main-container" class="container-fluid">
    <div class="col-xs-12">
        <div class="row" style="margin-bottom:4px;">
            <div class="col-md-1">
                <span style="font-size:11pt;font-weight:bold;">Entity Name:</span>
            </div>
            <div class="col-md-2">
                @Html.TextBoxFor(x => x.SearchEntityNameOrId, new { @type = "text", @placeholder = "Search", @class = "caAutoComplete_EntityEntityNameSearch", @style = "width:100%!important;" })
            </div>

        </div>
    </div>

Open in new window

0
I need to build a custom sort method for a GridView control, but I'm having trouble properly accessing the grid ID and the sort expression. Can some one give me an example of a custom sort method or links to one? I have to add many grids to my page and they all need to be sortable through one method.


        private void SortAllGrids(object sender, GridViewSortEventArgs e)
        {
            GridView gridView = (GridView)sender;
            string test = gridView.ID;           
        }

Open in new window

0
I have the following ajax call and controller.   I am getting the error message indicating
the parameters dictionary contains a null value for parameter "allocation" of non nullable type decimal for method system.web.jsonresult UpdateContactEntity(System.string, system.decimal,system.string,system.string) in contact controller.  An optional parameter but be a reference type, a nullable type, or be declared as an optional parameter.

Here is my ajax:  Note all the alerts pull a value..so this must be in the ajax call itself..perhaps with url

function UpdateContactEntity(clientxcontactId) {
    var allocation = $("#txtAllocation_" + clientxcontactId).val();  
    var role = $('#selectRole_' + clientxcontactId +' :selected').text();  
    var designate =  $('#selectDesignate_' + clientxcontactId +' :selected').text(); 
    alert(allocation); 
    alert(designate);
    alert(role);   
    alert(clientxcontactId);
   $.ajax({
        url: "/Contact.mvc/UpdateContactEntity/ " + clientxcontactId + "?allocation=" +  allocation + "?role=" +  role + "?designate=" +  designate,
        type: 'GET',
        cache: false,
        dataType: 'json',
        data: { data: clientxcontactId },
        success: function (data) {
                var result = $.trim(data.Result);              
                ShowGridRedraw();
                },
        error: function (request, status, error) {
        alert(request.responseText);
        }     
     });
}

Open in new window


And here is the call to the controller:

[System.Web.Mvc.HttpGet]
        public JsonResult UpdateContactEntity(string id, decimal allocation, string role, string designate)
        {
            var result = true;
            int clientxcontactId = id.ToInt32();

            IContactEntityEditService contactEntityEditService = DependencyResolver.Current.GetService<IContactEntityEditService>();

            var updated = contactEntityEditService.UpdateContactClient(clientxcontactId,allocation, role, designate);

            result = updated;
            return Json(result, JsonRequestBehavior.AllowGet);
        }

Open in new window

0
I am programming in C#. I have some data that I want to write to an HTML file as a table of 3 columns and an unknown number of rows.

Then I display that file in a web browser.

Currently this is all done by brute force. The C# code writes out the <HTML> tag and all the following header tags. It writes the <TABLE> tag. It loops through the data, writing each line of the table, adding appropriate <TR>...</TR> and <TD>...</TD> tags. It then closes the table with a </TABLE> tag, writes some footer information, and finally ends the file with a </HTML> tag.

There's got to be a better way.

This code works, but it's difficult to maintain.

I know PHP has a nice way of dealing with this, But I'm not using PHP, I'm using C#.

I've seen XSLT transformations that outputs nice HTML code, but my input isn't XML.

Is there a good way to deal with this in C#? Where I can create some sort of template that's easy to understand and maintain? A template that conveys the idea, "I want the output to be a HTML file which has a table of 3 columns"?
0
Free Tool: ZipGrep
LVL 11
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

I am trying to make an ajax  call...that will grab the values off the page...and then pass those values in the URL to the controller.

Here is the ajax...its crapping out on the 2nd line starting with var allocation.

function UpdateContactEntity(clientxcontactId) {
    var allocation = $("#txtallocation" + clientxcontactId + ).val();
    alert(allocation);       
   $.ajax({
        alert("test");
        url: "/Contact.mvc/UpdateContactEntity?clientxcontactId=" + clientxcontactId + "?allocation=" +  allocation,
        type: 'GET',
        cache: false,
        dataType: 'json',
        data: { data: clientxcontactId },
        success: function (data) {
                var result = $.trim(data.Result);              
                ShowGridRedraw();
                },
        error: function (request, status, error) {
        alert(request.responseText);
        }     
     });
}

Open in new window


For greater detail here is the other parts of my code:
Here is where I call it.

     [System.Web.Mvc.HttpGet]
        public JsonResult UpdateContactEntity(string data,int allocation)
        {
            var result = true;
            int clientxcontactId = data.ToInt32();
            IContactEntityEditService contactEntityEditService = DependencyResolver.Current.GetService<IContactEntityEditService>();

            var updated = contactEntityEditService.UpdateContactClient(clientxcontactId,allocation);

            result = updated;
            return Json(result, JsonRequestBehavior.AllowGet);
        }

Open in new window

0
Im having trouble with displaying the information with repeater, this is done with 2 projects, company and supplier. i used web service to get the information from supplier to company.

Error: the name 'dae does not exist in the current context' (.cs page at the company side)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PawsPawsMock.BLL;
using System.Data;
using System.Data.SqlClient;

namespace PawsPawsMock
{
    public partial class AdminECatalog : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindEventRepeater();
            }
        }
        private void BindEventRepeater()
        {
            BllCompEventCatalog eve = new BllCompEventCatalog();
            DataSet ds = new DataSet(); 
                DataTable dte = new DataTable();
                dae.Fill(dte);
                rptrEvents.DataSource = dte;
                rptrEvents.DataBind();
        }
    }
}

Open in new window

the aspx page(source):
 <asp:Repeater ID="rptrEvents" runat="server">
            <ItemTemplate>
                <div class="col-sm-3 col-md-3">
                    <div class="thumbnail">
                        <!--Add image here--->
                        <div class="caption">
                             <div class="proName"><%#Eval("EName") %></div>
                            <div class="proPrice"><span class="proOgPrice"><%#Eval("EPrice") %></span> <%#Eval("ESelName") %><span class="proPriceDiscount">(201 Off)</span></div>
                        </div>
                    </div>
                </div>
            </ItemTemplate>
        </asp:Repeater>

Open in new window

0
I have a DAL folder which has a Category.cs and i used the insert like this
  public int CategoryInsert()
        {
            StringBuilder sql;
            SqlCommand sqlCmd;
            int result;

            result = 0;
            sql = new StringBuilder();
            sql.AppendLine("INSERT INTO tblCategories (CatID, CatName)");
            sql.AppendLine(" ");
            sql.AppendLine("values (@CatName)");
            SqlConnection conn = dbConn.GetConnection();
            try
            {
                sqlCmd = new SqlCommand(sql.ToString(), conn);
                sqlCmd.Parameters.AddWithValue("@CatName", this.CatName);
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
            }
            finally
            {
                conn.Close();
            }

            return result;
        }

Open in new window

The code behind for my addCategory.aspx page is this
   protected void btnAdd_Click(object sender, EventArgs e)
        {
            Category eCategory = new Category(txtCatName.Text);

            if (eCategory.CategoryInsert() == 0)
            {
                Response.Write("<script>alert('Insert successful');</script>");
            }
            else
            {
                Response.Write("<script>alert('ID exists.Insert NOT successful.');</script>");
            }
        }

Open in new window

when i click add when i run, it says Insert successful but when i check in the database nothing is being inserted!!! I set the CatID to identity(1,1)
0
I came across an example, like below, where an interface is defined. then an abstract class is defined that implements this interface.

Now the concrete implementation class, both inherits and implements, base class and interface respectively.

Questions -

1. does it need to implement both?
2. the way I understand this is, this is being done for code reuse. so that any common implementation goes in the abstract class and concrete implementation don't have to provide their own implementation. based on that, why not just have abstract class?

public interface IWork {
       string workerName {get; set;}
       
       int CountHours();
       
       void DoWork();
}

public abstract class Work : IWork {

      public string workerName {get; set;}
     
      public int CountHourse(){
         //do some calculation
         //return result;
      }

      Public abstract void DoWork();
}

public class PrimaryWork : Work : IWork {
   
      public override void DoWork(){
            //do something
      }
}
0
I am trying to understand use cases where one would use interface hierarchy, something like below.

As my question sounds vague, if anyone can provide me, when and why someone would use this, with a real world example and explanation, that would be great.

public interface A{
}

public interface B : A {
}

public interface C : B{
}
0
I program in C# but need to write a Java app that can be downloaded and run on many platforms. The application will "scrub" confidential information from a merchant's credit card report (PDF).

It will remove the merchant's name, address, merchant ID (xxxx-xxxx-xxxx-xxxx) account number, etc.

It will do this by scanning the entire PDF and exporting non-confidential data to a CSV file.

I need this to be easy for non-techies to download and run.

What basic considerations should I have about what I should and should not consider before I start planning the design?

What frameworks help? Hurt?

What kind of installation program/script is needed?

I would host this download from my website...

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