Quantcast
Channel: Visual C# forum
Viewing all 31927 articles
Browse latest View live

C# - How to convert Excel sheet to data table dynamically

$
0
0

Hi,

I have the excel and i want to convert same structure format as datatable.

for example,

below is my screenshot and output.

The datatable should dynamically generate based on my excel column input.

for example.

if i have 5 excel columns then datatable only A to E,

if i have 3 excel columns then datatable only A to C, like that.

How to do this.??


From a property setter in my view model, can I change the Text property of a TextBox on my main window?

$
0
0

Sorry if the title is awkward, it's tricky for me to word this problem concisely.

In my view model I have three bools that are two-way bound to three radio buttons, here is one of them, the other two are identical but with different names:

private bool _calcNumsOff;
public bool CalcNumsOff
{
    get { return _calcNumsOff; }
    set
    {
         _calcNumsOff = value;
         OnPropertyChanged("CalcNumsOff");
     }
}

On my main window I have a TextBox and when the radio-buttons are changed I would like the TextBox's TextChanged event to fire, but keep the text that it contains. So I would imagine the simplest way to do that is just send the TextBox the content of its own Text property with something like: InputTextBox.Text = InputTextBox.Text;

I assume this would be done in the property's setter? My main issue though is the scoping, the class can't see the TextBox, so maybe I'm going about this all wrong?


How to convert Excel to data table in simple way..

$
0
0

I want to convert excel to data table.

Input template

Output data table

Note : eliminate the first 9 rows from the input template for the output. for output data, we need to consider only from row no. 10


How to input strings into a private List

$
0
0

Can somebody help me how to input strings in a private List<Book> in the main method??

Thank you so much in advance.

-Morena

public class Librarian { private List<Book> bookList; public void RegisterBook(List<Book> myRegisteredBook) { bookList = myRegisteredBook; } public List<Book> RegisteredBooks() { return bookList; } } class Program { static void Main(string[] args) { Bok myBook = new Book(); string bookTitle; string bookAuthor; int PublishingYear; Librarian newBook = new Libararian(); newBook.RegisterBook();//I need help here!!! List<Book> newBooks = newBook.RegisteredBooks();


Parsing HTML and getting the value of an element based on its ID

$
0
0

I'm executing an HttpWebRequest that grabs the HTML from a given URL. I'm receiving the HTML as expected, but I'm not sure of the best way to get the value of an element based on its ID.

Here's the HTML I receive:

<HTML><HEAD><TITLE>Device Status</TITLE></HEAD><BODY><div id="deviceValue">00</div></BODY></HTML>

I'm wanting to get 00 from the element with the ID: "deviceValue"

I'm assuming there has to be a super simple way to do this since people have been parsing HTML for decades but I can't find a such a simple solution.

Any ideas?

Thanks!

C# Gratuitous ARP - How to Implement

$
0
0

I Already implemented Sending ARP request using "iphlpapi.dll". 

[DllImport("iphlpapi.dll", ExactSpelling = true)]
private static extern int SendARP(uint DestIP, uint SrcIP, byte[] pMacAddr, ref int PhyAddrLen);

Now i need to Implement Gratuitous ARP. Could anyone help

Moving cursor/mouse out of the listBox caused highlighted item color change in WPF

$
0
0

Hi, we have listBox in the GUI and if we click an item, it's highlighted with blue color, but if we move the mouse/cursor outside of the listBox area, the highligt color disappear and turn to outlined (maybe default system highlight from what read somewhere).

Does anyone know how to fix this?


Thanks in advance!

how to apply multi threading to a method

$
0
0

I have a program that get user int input "1" and increment it based on the amount of files in a directory then stamp that int on each file( first is 1 and so on 1++). The foreach loop go in each directory gets its files, increment the input and call the stamp method until all files are done. In this process the order is important. However multitasking ( Parallel.ForEach) does't always guarantee order, in my understanding it returns which ever thread done first and maybe also damage the i++ functionality ( correct me if I'm wrong).

The question is how to apply multi threading in this case? i am thinking save the values of the foreach at the end, pass it to the stamping method and have the method stamp x amount of files at a time. I don't know if its possible or how to apply.

Here is my watermark method:

      //text comes from the foreach already set.
  public void waterMark(string text, string sourcePath, string destinationPathh)
        {
            using (Bitmap bitmap = new Bitmap(sourcePath))
            {
                int compressionTagIndex = Array.IndexOf(bitmap.PropertyIdList, 0x103);
                PropertyItem compressionTag = bitmap.PropertyItems[compressionTagIndex];
                byte[] com = compressionTag.Value;
                Encoder encoder = Encoder.Compression;
                EncoderParameters myEncoderParameters = new EncoderParameters(1);
                EncoderParameter myEncoderParameter = new EncoderParameter(encoder, (long)EncoderValue.CompressionCCITT4);
                myEncoderParameters.Param[0] = myEncoderParameter;
                ImageCodecInfo myImageCodecInfo;
                myImageCodecInfo = GetEncoderInfo("image/tiff");

                Brush brush = new SolidBrush(Color.Black);
                Font font = new Font("Arial", 50, FontStyle.Italic, GraphicsUnit.Pixel);
                Bitmap tempBitmap = new Bitmap(bitmap.Width, bitmap.Height);
                Graphics tempGraphics = Graphics.FromImage(tempBitmap);
                SizeF textSize = tempGraphics.MeasureString(text, font);
                tempBitmap = new Bitmap(bitmap.Width, bitmap.Height + (int)textSize.Height + 10);
                tempBitmap.SetResolution(bitmap.HorizontalResolution, bitmap.VerticalResolution);
                using (Graphics graphics = Graphics.FromImage(tempBitmap))
                {
                    graphics.FillRectangle(Brushes.White, 0, 0, bitmap.Width, bitmap.Height + 100);
                    graphics.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height);
                    Point position = new Point(bitmap.Width - ((int)textSize.Width + 200), bitmap.Height + 5);
                    graphics.DrawString((text), font, brush, position);
                    if (new[] { 2, 3, 4 }.Contains(com[0]))

                    {
                        tempBitmap.Save(destinationPathh, myImageCodecInfo, myEncoderParameters);
                        return;
                    }
                    tempBitmap.Save(destinationPathh, ImageFormat.Tiff);

                }
            }
        }
I can provide the foreach loop if needed. Thank you in advance.

  

IComparer vs Generic IComparer

$
0
0

Hello,

Which one is better at performance?

Thanks

   class SortYearAscending : IComparer
    {
        public int Compare(object x, object y)
        {
            Person P1 = (Person)x;
            Person P2 = (Person)y;

            if (P1.Year > P2.Year)
                return 1;
            else if (P1.Year < P2.Year)
                return -1;
            else return 0; 
        }
    }

And

    class SortYearAscending : IComparer<Person>
    {
        public int Compare(Person P1,Person P2)
        {
            if (P1.Year > P2.Year)
                return 1;
            else if (P1.Year < P2.Year)
                return -1;
            else return 0; 
        }
    }


DTS Script task Runtime Error During ssis script task Execution

$
0
0

Hi all,

I'm trying to develop an ssis packages which includes for loop & script task in it. I'm trying to look at file file in folder using script task(C#) , if flat file is present in folder , should execute other task. If flat file is not present in folder the process should wait for some minutes and check the folder again for the file. For this i'm using Visual studio 2019, SQL server 2016 as target version, Microsoft Visual C#2015 in script task.

When i'm executing the package i'm getting below error message.

    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean                      constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[]                       arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[]                  parameters,CultureInfo culture)
   at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target,                  Object[]providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
   at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()

below is script code

#region Namespaces
using System;
using System.Data;
using System.IO;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Threading;
#endregion

namespace ST_c937e73bb1724a9bae78f2ac13d34ca3
{
	[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
	public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
	{     
        public void Main()
        {
            string FileLocation;
            string[] Files;
            Int32 DelayTimer;
            Int32 result;

            result = 1;
            DelayTimer = (Int32)Dts.Variables["User:: DelayTimerInMS"].Value;
            FileLocation = (string)Dts.Variables["User::FileFolder"].Value.ToString();
            Files = Directory.GetFiles(FileLocation);
            string filepath = Dts.Variables["User::FileFolder"].Value.ToString();
            if (
                File.Exists(filepath))
            {
                MessageBox.Show("Data File Name:" + Files[0].ToString());
                Dts.Variables["User:FileExist"].Value = true;
                Dts.TaskResult = (int)ScriptResults.Success;
            }
            else
                Thread.Sleep(DelayTimer);

            Dts.TaskResult = (int)ScriptResults.Success;
        }

        #region ScriptResults declaration
        /// <summary>
        /// This enum provides a convenient shorthand within the scope of this class for setting the
        /// result of the script.
        /// 
        /// This code was generated automatically.
        /// </summary>
        enum ScriptResults
        {
            Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
            Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
        };
        #endregion

    }
}

Thanks

Is it possible to force the compilation of DynamicMethod

$
0
0

I'm working on a Json serialization solution. I found out that the serialization based on emitting was much faster than direct operations on Reflection api after the emitted code had already been run once(each time with different data). Obviously the problem is JIT. So I wonder wether there is a way to force the compilation of DynamicMethod. The PreJIT feature,provided by Runtime.CompilerServices.RuntimeHelpers.PrepareMethod, simply doesn‘t work because we have no access to RuntimeMethodHandle of DynamicMethod. So is there other way to achieve this goal?

Thanks in advance.



. Getting error C2079: IDBConnection uses unknown class

$
0
0

I am porting an application from VC6 to VS2015. when I am building after including all the header files I am getting the following error

Error C2079 'IDBConnection' uses undefined class 'MIDBODBC::__MIDBODBC_EXPORT_MODE__'

I have included the header file.. but still I get this.

The class where IDBConnection is declared is like this:

namespace MIDBODBC
{
class __MIDBODBC_EXPORT_MODE__ IDBConnection : public CObject
{
protected :
 CDatabase* m_pDBPtr;
 CMIPLOG  m_pLog;
 int   m_nDBConnectionIndex;
 int   m_nDBPoolWorkerIndex;

.....

.....

}

Can someone pl suggest how to tackle this error

Calling Visual studio Ver 6 DLL from Visual Studio 2015

$
0
0

I have a question. I have a project which has all individual C++ DLL 's. The entry point is a C# DLL which in turn calls all these C++ DLL'S .Now the OS environment has be migrated to VS 2015 and Windows 10.

I have a problem porting all these DLL's to VS 2015 as I do not have the complete source code. I was able to port the C# DLL.

Can I deploy the Migrated C# DLL along with the old Visual studio Version 6 DLL's in the environment. The backward compatability should be able to take care of this. Can you please let me know your views. We can have a separate Include header file and Lib file path for these old c++ DLL. awaiting your reply.

Couldn't generate excel using interop.excel component recently. Suspecting recent microsoft update cause this issue.

$
0
0

hi all,

I am getting following error while try to generate the excel using interop.excel component but I could generate excel previously. This error occurred to many users recently those can able to generate the report previously. I am suspecting some microsoft updates cause this issue. If anyone experience this issue please help me to overcome this.

Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass' to interface type 'Microsoft.Office.Interop.Excel._Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208D5-0000-0000-C000-000000000046}' failed due to the following error: Library not registered. (Exception from HRESULT: 0x8002801D (TYPE_E_LIBNOTREGISTERED)).

Thanks

Arivazhagan K

Unable to authenticate user from custom MVC Web application against Azure Active Directory

$
0
0

Not able to authenticate MVC application users with Azure Active Directory. When try to sign-in, it gives error: 'We couldn't sign you in. Please try again later'. Azure AD configurations in both application and and Azure AD tenant account are proper. But still getting this error. getting the error for all users in AD. There are no any additional details in logs. I Azure AD user's sign-in logs it says status as 'Success' but still not able to get in

Please suggest. Its urgent and critical

Thanks in advance


how to create virtual com port creation software in c#

$
0
0

i have been assigned a task to create a windows software , that have to create a virtual com port ,that should be visible in pc's device manager as virtual com xx.

with that software we are going to communicating to another existing software.that existing one only can communicate with com port only. so we have to create a virtual com port by my own software.

please do not suggest third party software....

is there any visual studio c# code available?....(visual studio windows form application)

i hope u are   understand my qus and respond soon,,,,,,,,,

asp.net mvc & asp.net core & c#

$
0
0

i do hope that i am posting in the right place.

i am new to programming and goggled before posting here and found myself confused.

what i have learned so far is:

  • c# is the programming language.
  • asp.net mvc is the way to manage the server.
  • asp.net core ... i am really have no clue about it and i do not know the differences between themvc and core.
  • both 3 are part of the .net (.net which is something i am still not comfortable with completely).

i want to learn from scratch so please give me just titles of books to buy to read and learn and please note that these books should be for beginner because most books i've checked assume programming background which i do not have.

please i want to learn in my own and i am not lazy but confused for what to do in terms of books.

i did checked some titles from microsoft press but when i read the section who should read this book i found it assuming reader has programming knowledge.

thanks

How to read specific field value when using LINQ to object to fetch data

$
0
0

see ny code

                    var data = dtFilterDataFromAllData.AsEnumerable().Where(x => x.Field<string>("Tab").ToString().Trim() == strBRTab&& x.Field<string>("Broker Items").ToString() == strBRLineItem&& x.Field<string>("Row").ToString().Trim() == RowNumber)
                        .Select(w => new { LinkText = w.Field<string>("LinkedItemList"), AllowBlank = w.Field<string>("Allow Blank in Calc.") }).ToList();
where i am using LINQ on datatable to select data for two fields called LinkedItemList & Allow Blank in Calc.

without using foreach how to read data from data variable like array like access ?

how to read data like data["LinkedItemList"] 

please tell me the way without foreach or for. thanks

SOAP request with headers

$
0
0

Hi,

I don't know if tis is the right place to ask (correct me if I'm wrong), but I have to make a soap request with the authorization in the 'Header'. I worked already a lot with webservices but I never had to make a request with a customized header. It's a WSDL link I received, so it must be SOAP I guess. But I have no idea where to start.

Any ideas are very much appreciated.

Thanks !!

^ Operator in C#

$
0
0

Hello,

I have two question

1. What do do we call ^ in English and programming languages?

2. How can ^margin and ^amountToTakeFromEnd and ^0  calculate?

Thanks in advance

int margin = 1;
int[] inner = numbers[margin..^margin];
Display(inner);  // output: 10 20 30 40

string line = "one two three";
int amountToTakeFromEnd = 5;
Range endIndices = ^amountToTakeFromEnd..^0;
string end = line[endIndices];



Viewing all 31927 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>