[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

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

Using these two pieces of code how would I get the PublicKeyToken for a dll called Dynamics.Application.dll? How do I pass the name down as an argument?

using System;
using System.Reflection;

namespace EE_Q29126560
{
      class Program
      {
            static void Main(string[] args)
            {
                  Console.WriteLine($"Object Assembly PublicKeyToken: {GetPublicKeyTokenFromAssembly(Assembly.GetAssembly(typeof(object)))}");
                  Console.ReadLine();
            }

            static string GetPublicKeyTokenFromAssembly(Assembly assembly)
            {
                  var bytes = assembly.GetName().GetPublicKeyToken();
                  if (bytes == null || bytes.Length == 0)
                        return "None";

                  var result = string.Empty;
                  for (int i = 0; i < bytes.GetLength(0); i++)
                        result += $"{bytes[i]:x2}";
                  return result;
            }
      }
}
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 need to find the PublicKeyToken of an assembly called Application.Dynamics

Here is my method for getting the public key token.
====================================================================================================================
        private static string GetPublicKeyTokenFromAssembly(Assembly assembly)
        {
            var bytes = assembly.GetName().GetPublicKeyToken();
            if (bytes == null || bytes.Length == 0)
                return "None";

            var publicKeyToken = string.Empty;
            for (int i = 0; i < bytes.GetLength(0); i++)
                publicKeyToken += string.Format("{0:x2}", bytes[i]);
            return publicKeyToken;
        }

===================================================================================
The question is how to I assign this value to a string?
string TokenString = GetPublicKeyTokenFromAssembly("Application.Dynamics");

This does not work. I get a message about not being able to convert a string to an assembly reference.
How do structure so I can see the value of the Public Key Token of this assembly?
0
In C# I have a WPF textbox in my form, a added a contextmenu:
  <TextBox.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Cut" Click="menu_cut"  />
                <MenuItem Header="Copy" Click="menu_copy"  />
                <MenuItem Header="Paste" Click="menu_paste"  />
            </ContextMenu>
 </TextBox.ContextMenu>
I have html table in browser that look as a picture "file1" in attachment
when I  copy to *.doc I got as a picture "file2"

If I use code:
 private void menu_paste(object sender, RoutedEventArgs e)
        {
            if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) == true)
            {
                 memo_text.Text = memo_text.Text + Clipboard.GetText(TextDataFormat.Text);
               
            }
        }

I got a picture "file3"

If I use code:
 private void menu_paste(object sender, RoutedEventArgs e)
        {
            if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) == true)
            {
                 memo_text.Text = memo_text.Text + Clipboard.GetText(TextDataFormat.Html);
               
            }
        }

I got a picture "file5"

when I use *.doc intermediately and  copy to textbox, result as picture "file4"
How can I get format as "file4" directly?
file1.JPG
file2.JPG
file3.JPG
file4.JPG
file5.JPG
0
I have a simple C# WPF application that shows production data in a datagrid that is bound to a tableadapter in a dataset linked to a SQL database table.  The only function is to display this information 24/7, it is not used to add or edit data.  My question is pretty general, what is the best way to ensure this application keeps running?  Every now and then it will stop working until I reopen the application.  Perhaps the way to handle it is to just relaunch the app any time it throws an exception?  The only message I get right now when it crashes is "Production Counter has stopped working.".

I'm new to C# and I am interested in your opinions/sample code/ideas, I'm looking to learn.  Thank you!

namespace ProductionCounter
{

    public partial class MainWindow : Window
    {
        public DispatcherTimer _timer = null;
        public MainWindow()
        {
            InitializeComponent();
            Initializeload();

            // Start the timer to refresh every 10000ms thereafter (change as required)
            _timer = new DispatcherTimer();
            _timer.Tick += Each_Tick;
            _timer.Interval = new TimeSpan(0, 0, 0, 0, 10000);
            _timer.Start();

            var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            lblVersion.Content = string.Format("Version {0}", version);

            string machineName = Environment.MachineName;            
            lblMachineName.Content = machineName;
  

Open in new window

0
I have an owner_drawn list view

this.ViewInstalledFiles.OwnerDraw = true;
this.ViewInstalledFiles.DrawSubItem += new System.Windows.Forms.DrawListViewSubItemEventHandler(this.ViewInstalledFiles_DrawSubItem);


But the event handler is never called even if I call             ViewInstalledFiles.Invalidate();

How to I ensure it is called please?
0
I''m getting the following error on my for each loop on the TempData["test"] and I'm note sure how I should resolve this.

System.InvalidCastException: 'Unable to cast object of type 'xxx.Models.CustomReports.ServiceSumaryResultsContainer' to type 'System.Collections.Generic.List`1[xxx.Models.CustomReports.ServiceSummaryResults]'.'

foreach (var item in (List<ServiceSummaryResults>)TempData["test"])
            {
                    var data = String.Join(",", new string[]
                    {

                        item.RouteCode,
                     
                    });

                    sb.AppendLine(data);
                }

Open in new window


Also I have included my model:


namespace XXX.Models.CustomReports
{
    public class ServiceSummarySearchCriteria : CustomReportsSearchCriteria
    {
        public ServiceSummarySearchCriteria()
        {
            this.ReportDateRange = new DateRangeObject();
            this.ReportDateRange.RangeText = "This year-to-date";
        }
        public bool AllServiceCodes { get; set; }
        public bool AllZipCodes { get; set; }
        public int Season { get; set; }
        public string[] SelectedServiceCodes { get; set; }
        public string[] SelectedCustomerStatuses { get; set; }
        public string[] SelectedZipCodes { get; set; }
        public DateRangeObject ReportDateRange { get; set; }
    }

      public class ServiceSumaryReportResult
       {
         public 

Open in new window

0
I'm trying to understand Linq a bit better and came across this.
What is the ++ doing in data[x++]?  When setting up a for or foreach loop ++ increments the variable by 1.

            var data = new[] { 1, 2, 3 };
            var qry = from i in data select i * i;
            var x = 0;
            foreach (var result in qry)
            {
                 data[x++] = result;
              
            }
            foreach (var result in qry)
            {
                Console.WriteLine(result);
            }

Open in new window

0
Why does this code return 2 and not 4?  The new keyword makes no difference except for a warning message when I remove it.
I could get 4 if I made the class A method virtual and the class B method an override.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp4
{
    public delegate void Foo();
    class Program
    {
        static void Main(string[] args)
        {
            A obj = new B();
            obj.Foo();
        }
        class A
        {
            public  void Foo()
            {
                Console.WriteLine("2");
            }
        }
        class B : A
        {
            public new void Foo()
            {
                Console.WriteLine("4");
            }
        }
    }
}

Open in new window

0
I have a text box, for user input. I read the user input,  and run a sql query in the back end , as such
 
select * from table where column like "%userinput%".

what should I do before including , the user input to the sql query , in order to prevent sql injection.

I am using C# and oracle database.
0
We have a site and it has a global search feature which is very very slow. It looks up 4 tables and does a wildcard.

This is how it looks like
select ....
 from 
 [dbo].[Unit] AS u
	LEFT join [dbo].[Schedule] AS s
    ON u.[ScheduleID] = s.[ID]
    LEFT OUTER JOIN [dbo].[MasterLease] AS m
        ON s.[MasterLeaseID] = m.[ID]
		INNER JOIN dbo.Portfolio p ON p.ID = m.PortfolioID
 
WHERE 
u.[Deleted] <> 1
          AND (1 <> s.[Status])
   
          AND (m.[Deleted] <> 1)
          AND (m.[Active] = 1)
AND
      (
          (s.[Sched] LIKE @searchtext)
          OR (u.[SerialNo] LIKE @searchtext)
        
          OR (u.[CustomerRef] LIKE @searchtext )
          OR (u.[Model] LIKE @searchtext )
          OR (u.[Manufacturer] LIKE @searchtext)
          OR (u.[SiteAddress] LIKE @searchtext )
          OR (m.[CustomerName] LIKE @searchtext )
          OR (s.[LesseeName] LIKE @searchtext )
      );

Open in new window


1. My manager doesn't want to do a FullText Search
2. We have used indexes
3. The wildcard slows down the search, I think
4. If I join the 4 tables without the where clause, I get 2,827,623 rows. Should we dump this data in a table and just search this table? (update the table every night with fresh data)
5. Tried this as well... I broke down the joins by creating temp tables. First search Units, dumped in the temp table, #Units. Then Schedules in #Scheudles , then MasterLease in #ML.  Then did the join like I have above but what if there's nothing in #Units table...meaning...search didn't bring anything back from and #units is empty. I don't the join going to be correct.

I think #4 is a good option. How do others do a global search?
0
Fundamentals of JavaScript
LVL 12
Fundamentals of JavaScript

Learn the fundamentals of the popular programming language JavaScript so that you can explore the realm of web development.

How to loop through an Array in Java script where i am getting data from c# code as dictionary

private Dictionary<string, object> _dic = new Dictionary<string, object>();

        public Dictionary<string, object> dic
        {
            get
            {
                return _dic;
            }
            protected set
            {
                _dic = value;
            }
        }
 public string MyDictionaryToJson()
        {
            string jsonString = (new JavaScriptSerializer()).Serialize((object)_dic);
            return jsonString;
            //var entries = _dic.Select(d =>
            //    string.Format("\"{0}\": [{1}]", d.Key, string.Join(",", d.Value)));
            //return "{" + string.Join(",", entries) + "}";
        }
        private static Random random = new Random();
        public static string RandomString(int length)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            return new string(Enumerable.Repeat(chars, length)
              .Select(s => s[random.Next(s.Length)]).ToArray());
        }
        private DataTable BindData()
        {
            


            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("ColId", typeof(string));
            dataTable.Columns.Add("ColValue", typeof(string));

            for (int i = 0; i < 50000; i++)
            {
                dataTable.Rows.Add(i.ToString(), RandomString(5));

            }
            foreach 

Open in new window

1
Hello Folks,

I'm expanding my knowledge in learning classes in powershell... I have written this basic  PS example

class Books {
    [string]$title 
    [string]$author
    [int]$pages   
}

$books1 = [books]::new()
$books1.title = "Harry Potter"
$books1.author = "JK Rowling"
$books1.pages = 309

$books2 = [books]::new()
$books2.title = "Scott Pilgrim vs. the World"
$books2.author = "Bryan Lee O'Malley"
$books2.pages = 168

$books2 | ? {$_.title -like "*scott*"}

Open in new window


this will display the book from book 2 titled like "scott"...
Does anybody have any idea on how can I tell the program to search within all the books and find any "X" Title... I was thinking "foreach" but i'm not sure I could squeeze it in...? or if you have a c# approach that would be great also :)

Thanks in advance!
0
I'm following this example https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.1
to learn .Net Core.

I know LINQ to SQL is not supported in .Net Core. Is LINQ to Entities (LINQ to Entities ) supported? is my only option is to use Entity Framework?

(I really liked LINQ to SQL. Too bad it's not supported)
0
Hello Experts,
I am trying to generate an output file using StreamWriter in C# which contains Credit Card (CC) numbers.  As long as the CC Number is 15 digits long, the StreamWriter works just fine.  But when the CC Number length is 16 digits long, the StreamWriter replaces the last digit with 0 (zero).  Any idea how to fix it?  Please try to help.

Thank you very much in advance!
0
I have legacy code in C#, Web Forms and LINQ to SQL.

I want to upgrade this code and I want to move the data layer to ASP.Net Web API. I found this link
https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.1

I wanted to keep LINQ to SQL code (DBML) to make the upgrade go faster. Looks like LINQ to SQL is not supported in .Net Core.L2S not supported lin

What should I do? I have DBML, stored procs. How can I do my upgrade?
0
I pull data from a .CSV file that I dump into a multi-dim array.
I reformat array (into the final array) and then create an excel file and set all the column/row formatting.
In the final process, I dump parts of the array into structures columns.
I am using using Excel = Microsoft.Office.Interop.Excel;

The interaction with Excel seems to take longer than it should.

Using Interop to communicate with excel the most efficient/fastest way?

    int j = 2;
    oSheet.Range["A7:P" + rplUpdatedData.GetLength(0)].Borders.LineStyle = XlLineStyle.xlContinuous;
    for (int i = 7; i < rplUpdatedData.GetLength(0); i++)//i for Column index.
    {  

	oSheet.Cells[i, 1].value = rplUpdatedData[j, 0];
	oSheet.Cells[i, 2].value = rplUpdatedData[j, 3];
	oSheet.Cells[i, 3].value = rplUpdatedData[j, 4];
	oSheet.Cells[i, 4].value = rplUpdatedData[j, 15];
	oSheet.Cells[i, 5].value = rplUpdatedData[j, 24];
	oSheet.Cells[i, 6].value = rplUpdatedData[j, 6];
	oSheet.Cells[i, 7].value = rplUpdatedData[j, 26];
	oSheet.Cells[i, 8].value = rplUpdatedData[j, 8]; 
	oSheet.Cells[i, 9].value = rplUpdatedData[j, 28];
	oSheet.Cells[i, 10].value = rplUpdatedData[j, 30];
	oSheet.Cells[i, 11].value = rplUpdatedData[j, 12];
	oSheet.Cells[i, 13].value = rplUpdatedData[j, 26];
	oSheet.Cells[i, 14].value = rplUpdatedData[j, 16];
	oSheet.Cells[i, 15].value = rplUpdatedData[j, 1];
	oSheet.Cells[i, 16].value = rplUpdatedData[j, 2];

	j++;
    }

Open in new window


Thanks
Jed-
0
These two lines of vb6 code I am trying to translate to C#:

mskFromDate.Text = Format(Date - TimeSerial((iNumDaysBefore * 24), 0, 0), "Short Date")
    mskToDate.Text = Format(Date + TimeSerial((iNumDaysAfter * 24), 0, 0), "Short Date")

I have this so far. I know it is not right.

var dt = string.Empty;
                dt = Convert.ToString(DateTime.Now.ToOADate() - (NumDaysBefore * 24));
                this.dtFromDate.Text = Convert.ToDateTime(dt).ToShortDateString();

Anybody have thoughts? I can't believe in vb6 they let folks subtract dates and numbers.
0
I saw this question on when to use multi tasking rather than multithreading.
https://stackoverflow.com/questions/4130194/what-is-the-difference-between-task-and-thread
When are tasks not going to work, so that we must use multi threading?
I'm using C# version 6 with Visual Studio 2017.
0
Hi,
I have a batch file as below:
call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools\VsDevCmd.bat"
cd C:\AutomationTestSamples\AutomationTestSamples\bin\Debug
start cmd /k vstest.console.exe AutomationTestSamples.dll /Logger:trx;LogFileName=%1/UnitTest1.trx /testcasefilter:FullyQualifiedName~AutomationTestSamples.UnitTest1.trx

Open in new window


I want to read a batch file line by line and if the line contains "UnitTest1.trx",
I want to replace "/testcasefilter:FullyQualifiedName~AutomationTestSamples.UnitTest1" with "/test".

I tried the following code but when I opened the file nothing was replaced.  Any idea please?
string[] str = File.ReadAllLines(@"C:\Test\test.bat");
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i].Contains(trxName))
                {
                    str[i].Replace(str[i].Substring(str[i].IndexOf("/testcasefilter")), "/test");                    
                }
                
            }

Open in new window

0
Build an E-Commerce Site with Angular 5
LVL 12
Build an E-Commerce Site with Angular 5

Learn how to build an E-Commerce site with Angular 5, a JavaScript framework used by developers to build web, desktop, and mobile applications.

For some reason I cannot get the URI to locate a file.

Stream stream = Application.GetResourceStream(new Uri("D:\\MultipageDocument.pdf", UriKind.Relative)).Stream;

Here is where it bombs regardless of what I try to use; we have tried embedding into the app, use a drive letter, Relative, Absolute, nothing works.  We are getting "Cannot find resource" when it is truly there.

Stream stream = Application.GetResourceStream(new Uri("Viewer_PDF, PDF/MultipageDocument.pdf", UriKind.Relative)).Stream;

Any help would be greatly appreciated.
0
Hi All,
I have a C# DLL which was written for me to interface with my VB6 program.  The DLL is COM-Visible and the Register for COM interop selected.  The DLL has 3 methods Initialization, Up and Dn.

I have a small VB6 test program which access the DLL.

I'm using VS 2017 (run as administrator) to build the DLL
I have Visual Studio (VB6) on the same machine - A Windows 10 PRO system.

In my VB program I have a reference to the DLL (actually the TLB).  Intellesense works fine - I can see all three methods.
My startup code is:
Public Sub Main()
    Dim AM as AudioManager
    Set AM = New AudioManager       ' <<<==== Error here
  
End Sub

Open in new window

When I run the program I get an error at the Set statement - Runtime 429 - "ActiveX component can't create object".
I've done quite a bit of research on the web about this, and most of the similar issues are when someone tries to move a project from a development environment.  In my case , I'm getting this on the development system.
I have tried:
Tlbexp AM.DLL /out:AM.tlb
Regasm /tlb:AM.tlb AM.DLL
Gacutil /i AM.DLL
So far nothing seems to work.  I have put the DLL and TLB into the System32, SYSWOW64 and my VB6 application folders (registering it in each after removing from the previous location) - doesn't help.
Anyone have any ideas?
Thanks in advance
0
https://stackoverflow.com/questions/615950/how-do-i-access-a-control-in-the-headertemplate-of-my-gridview

In the above link there is this example:

Which uses FindControl to find a TextBox found in the HeaderTemplate of a ASP.NET Web Forms GridView.

GridView.PNG
Notice how it uses HeaderRow like this:  GV1.HeaderRow

I'm working on an old legacy web app which uses the older ASP.NET Web Forms DataGrid

DataGrid does not have HeaderRow.


What's the equivalent to these 2 lines for a DataGrid ?

        GridView GV1 = (GridView)FindControl("Lab_1_GV1");
        TextBox TXB1 = (TextBox)GV1.HeaderRow.FindControl("Lab_1_TX2GV1");
0
Hi

I have created an application that adds permissions to a Shared Folder on a Window server (this is important as I'm setting permissions on a share and NOT NTFS).

I now need to do the opposite and remove the group 'Everyone' from the Share permission.  I have a piece of code that gets the existing permissions as follows:

 Dim securityDescriptor As ManagementBaseObject = TryCast(securityDescriptorObject.Properties("Descriptor").Value, ManagementBaseObject)
        Dim existingAcessControlEntriesCount As Integer = 0
        Dim accessControlList As ManagementBaseObject() = TryCast(securityDescriptor.Properties("DACL").Value, ManagementBaseObject())

        If accessControlList Is Nothing Then
            accessControlList = New ManagementBaseObject(0) {}
        Else
            existingAcessControlEntriesCount = accessControlList.Length
            Array.Resize(accessControlList, accessControlList.Length + 1)
        End If

As you can see above, I am using an ACL list and I extend it  so that I can then add the new ACL for the group I want to give permissions to.  I now wish to do the opposite and remove an entry from the accessControlList.

Now, I am convinced that if I were to remove one of the existing entries from this accessControlList before committing it back, that would remove a permission for an existing object but I don't know how to enumerate the accessControlList to find the entry I want to remove.

In pseudo-code, this is what I …
0
I am writing an app that will collect data from a number of excel spreadsheets and create one spreadsheet with specific data.  I've attached an example of the data.

I am using ExcelDataReader to get the data and then dumping into a datatable.

I need to get the manufacturer, supplier, and price.  As you can see by the image that they can be in any position in the spreadsheet and also not all have all the information.  I was using a
foreach (Datarow dr in dt.rows)
{
    dr[0] .....
}

Open in new window

Anyone have any suggestions to get the data in an easier manner than checking each column to then get all pertinent data in subsequent rows?

material example
0
I don't think ASP.Net app pool queues database calls but this is what my manager says:

We had a deadlock on a table. He said we don't get a deadlock on whatever section of the code because ASP.Net App Pool queues the select statements and that's why we don't get a deadlock in one section and we get it in another section.

Doesn't make sense to me. I think he was making it up :)
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).