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

Excel automation naming conflict “_FilterDatabase” - different behavior MFC ole automation vs. C# .NET

$
0
0

Opening an Excel document by C++ MFC OLE automation shows a naming conflict ("_FilterDatabase") while the similar approach in C# .NET via Microsoft.Office.Interop.Excel does not.

n my C++ MFC OLE Automation project I have imported the type library for excel.exe and selected the interfaces _Applicatin (CExcelApplication), _Workbook(CWorkbook) and Workbooks(CWorkbooks).

Opening an Excel document by C++ MFC OLE automation shows a naming conflict ("_FilterDatabase") while the similar approach in C# .NET via Microsoft.Office.Interop.Excel does not.

In my C++ MFC OLE Automation project I have imported the type library for excel.exe and selected the interfaces _Applicatin (CExcelApplication), _Workbook(CWorkbook) and Workbooks(CWorkbooks).

In my C# .NET project I have added the COM reference "Microsoft Excel 16.0 Object Library".

This is the code I'm using in the C++ MFC OLE automation project:

void OpenExcelDocument(const std::wstring& strDocument)
{

    // Create Excel object and bring Excel to the screen
    CExcelApplication appExcel;
    appExcel.CreateDispatch(L"Excel.Application");

    appExcel.put_Visible(TRUE);


    // obtain the Workbooks interface
    LPDISPATCH pDispWorkbooks = appExcel.get_Workbooks();

    if (pDispWorkbooks == NULL)
        return;

    CExcelWorkbooks workbooks;
    workbooks.AttachDispatch(pDispWorkbooks);

    // setup the default parameters
    VARIANT varDefault;
    memset(&varDefault, 0, sizeof(varDefault));
    varDefault.vt = VT_ERROR;
    varDefault.scode = DISP_E_PARAMNOTFOUND;

    // open the document
    workbooks.Open(strDocument.c_str(),
        varDefault, varDefault, varDefault, varDefault, varDefault, varDefault, varDefault, varDefault,
        varDefault, varDefault, varDefault, varDefault, varDefault, varDefault);

} 

The following code shows the similar approach via C# .NET

using Excel = Microsoft.Office.Interop.Excel;

namespace ReadExcelDoc
{
    class Program
    {

        static void OpenExcelDocument(String strDocument)
        {
            Excel.Application xlApp = new Excel.Application();
            xlApp.Visible = true;

            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(strDocument);
        }

        static void Main(string[] args)
        {
            String xlsFile = @"..."; 
            OpenExcelDocument(xlsFile); 
        }
    }
}

My questions are:

  • Is this really internally the same approach for the Excel COM objects?
  • Is there a way to avoid Excel prompting to resolve the naming conflict in my C++ MFC OLE automation approach despite altering the Excel document manually?
  • Are my VARIANT default arguments in C++ specified correctly?



OAuth 2.0 for HMRC

$
0
0

I'm designing an application that is going to connect to HMRC (UK Tax office for those not in the UK). They use OAuth 2.0. As is typical with Government web services, the documentation is convoluted to say the least. Most docs and posts I read about OAuth demonstrate how to do the server side bit. Well, this application will be the client and it will take data from a database, store it in an object, then post it to an endpoint URL with a json body containing the data, and wait for a response. In principle, relatively simple. However, I am stuck at the start with setting up OAuth and what is needed. I've read tonnes of documentation and I end up going around in circles.

They do have a github and I'll be honest, I don't understand how github works.

I don't see how I can write the client side of an OAuth connection without having a server side to test it with. Any help with OAuth would be great. I'm writing this in VS2017 C# and it will be a Windows Forms application. Any help with what the best template would be, or what Nuget packages you'd recommend, would be gratefully appreciated.

How to automatically change the datetimepickervalue in winform c#?

$
0
0
I want to update the value of datetimepicker automatically till the application is open.

usb communication using c#

$
0
0

hello, 

good morning

in my application i need to communicate with usb using c# in windows forms applications. how to send data to usb and how to receive data from usb

please help me

Thanks and Regards

Rajani B

Getting Error : Cannot convert lambda expression to type

$
0
0

I have two winform application like app1 and app2 which are very similar and code also very similar. i copied few forms and code from app1 to app2 and when compile then i started getting below error.

Error      1061       Cannot convert lambda expression to type 'System.Collections.Generic.IEqualityComparer<RDSS_Workbench.QcVerticalViewNew.QcVerticalViewNewProcess.TickerBrokerStandardDateLineitemValue>' because it is not a delegate type              

 

 this is the code from where error was throwing

var TickerBrokerStandardDateLineitemValueAllBrokerBogeyDistinct = (from data1 in allTickerBrokerStandardDateLineitemValue2

   select new TickerBrokerStandardDateLineitemValue

   {

       TabName = data1.TabName,

       StandardLineItem = data1.StandardLineItem,

       BRTab = "",

       BRLineItem = "",

       Action = "",

       StandardValue = "",

       BrokerName = data1.BrokerName,

       CalValue = "",

   }).DistinctBy(x => new { x.TabName, x.StandardLineItem, x.BrokerName }).ToList();



var resultNotPersentInAllBrokerBogey = StandardBorgeyForEachBroker.Except(TickerBrokerStandardDateLineitemValueAllBrokerBogeyDistinct, (x, y) => x.TabName.Equals(y.TabName)&& x.StandardLineItem.Equals(y.StandardLineItem)&& x.BrokerName.Equals(y.BrokerName)).DistinctBy(x => new { x.TabName, x.StandardLineItem, x.BrokerName }).ToList();



allTickerBrokerStandardDateLineitemValue2.AddRange(resultNotPersentInAllBrokerBogey);

this below line was throwing error actually

var resultNotPersentInAllBrokerBogey = StandardBorgeyForEachBroker.Except

(TickerBrokerStandardDateLineitemValueAllBrokerBogeyDistinct, (x, y) => x.TabName.Equals(y.TabName)&& x.StandardLineItem.Equals(y.StandardLineItem)&& x.BrokerName.Equals(y.BrokerName)).DistinctBy(x => new

{ x.TabName, x.StandardLineItem, x.BrokerName }).ToList();

this line showing squiggle red (x, y)

i really do not understand what was missing in app2 which was causing this error the same code was working fine in app1. so anyone can tell me what i was missing ?

please help me sort the error.



Moving a Record after the record is marked delivered

$
0
0

Hi,

Haven't found the right answer for this, and don't know if im searching for the right question..

I have two databases, where database 1 contains orders for delivery. And database 2 is a database of delivered orders.

Now, I want to move the record from database 1 to database 2 after the record is marked delivered.

Is there a good way to do this?

My Applications is just a simple Windows Forms App.

Recreate Dynamic TextBox

$
0
0

I have a page that will dynamically create text boxes based on a NumberOfFilesValue and place them in a placeholder. This page might postback a few times as the user changes values on the page. I'm not able to find the placeholder in Pre_Init. 

using DataServices_v2.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DataServices_v2
{
	public partial class test : System.Web.UI.Page
	{
        protected void Page_PreInit(object sender, EventArgs e)
        {
            List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("Filename")).ToList();
            foreach (string key in keys)
            {
                AddTextBoxRow tbRow = new AddTextBoxRow();
                FilenamePlaceholder.Controls.Add(tbRow.NewRow(key));
            }
        }

        protected void Page_Load(object sender, EventArgs e)
		{
            //
		}

        protected void NumberOfFilesValue_TextChanged(object sender, EventArgs e)
        {
            FilenamePlaceholder.Controls.Clear();
            int file_count = Convert.ToInt16(NumberOfFilesValue.Text);
            string pre = "Filename ";
            for (int i = 1; i <= file_count; i++)
            {
                string control_text = pre + i.ToString();
                AddTextBoxRow tbRow = new AddTextBoxRow();
                FilenamePlaceholder.Controls.Add(tbRow.NewRow(control_text));
            }
        }

        protected void BatchSubmit_Click(object sender, EventArgs e)
        {

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using DataServices_v2.Mover;

namespace DataServices_v2.Shared
{
    public class AddTextBoxRow
    {

        public HtmlGenericControl NewRow(string ControlText)
        {
            HtmlGenericControl main_div = new HtmlGenericControl("div"); //main div
            main_div.Attributes["class"] = "form-group";

            Label l = new Label
            {
                ID = ControlText.Replace(" ", String.Empty) + "Label",
                Text = ControlText,
                CssClass = "control-label col-md-2"
            };
            main_div.Controls.Add(l); //add label to main div

            HtmlGenericControl value_div = new HtmlGenericControl("div"); //secondary div
            value_div.Attributes["class"] = "col-md-10";

            TextBox tb = new TextBox
            {
                ID = ControlText.Replace(" ",String.Empty) + "Value",
                CssClass = "form-control"
            };
            value_div.Controls.Add(tb);

            main_div.Controls.Add(value_div); //add secondary div to main div
            return main_div;
        }               

                

                

                

                
    }
}

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="DataServices_v2.test" %><asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server"><div class="form-group"><asp:Label ID="NumberOfFilesLabel" runat="server" Text="Number of Files" CssClass="control-label col-md-2" /><div class="col-md-10"><asp:TextBox ID="NumberOfFilesValue" runat="server" OnTextChanged="NumberOfFilesValue_TextChanged" AutoPostBack="true" CssClass="form-control" style="width:50px" /></div></div><asp:Panel ID="FilenamePlaceholder" runat="server" /><hr /><div class="form-group"><div class="col-md-offset-2 col-md-10"><asp:Button ID="BatchSubmit" runat="server" Text="Create Files" OnClick="BatchSubmit_Click" CssClass="btn btn-default" /></div></div></asp:Content>

How to user var as public variable?

$
0
0

Hi all,

to use variable stored in MainWindow from some Page I use this method ...

var mw = Application.Current.Windows
        .Cast<Window>()
        .FirstOrDefault(window => window is MainWindow) as MainWindow;

But I need to use these line in every function in Page. More simple it would be If there was a one public variable.  Or is there a more simple way of how to do this? ... of how to use variables between window - page?

Thank you.


(CssLint)Rule is empty

$
0
0

I'm revamping a web site I built a few years ago in VS 2015, but now I have VS 2017, and doing lots of cleanup, like adding the slashes to the end of input tags and the like.

There is one I don't understand: It's giving me an error in my style.css file at the body tag: (CssLint)Rule is empty.

My body tag looks like this:

body {
    margin: 0;
    padding: 0;
    background: #28281F url(img01.jpg) repeat-x left top;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 14px;
    color: #19130D;
}
It doesn't seem to complain about the others.

Accessing a DB table from different process

$
0
0

I have two different background process.

The one is read/write record from/to the table A and another process read/write from/to the same table.

The DB is MS Access 2012.

Is it safe to access the DB table from two different process?

Should I do extra work to do this job from code?

Weird Glitch (maybe) with random number generator

$
0
0

Hi, as a part of one of my projects I am making a random number generator. The code for it is below. It takes a Maximum number, a list of numbers that should be excluded, and an array (I think that's the proper terminology I'm new) (to dump the numbers to and dictate how many numbers it should generate).

Anyways, when I run this slowly through the debugger, it works as expected. However, when I run it normally through visual studio without any breaks, I get numbers that are all right next to each other (example: 200, 202, 201, 203, 205), where I would be expecting a result like 305, 684, 126, 984, 235.

I don't know why this is happening and was wondering if I am doing anything wrong or if it's a glitch. Any help would be appreciated.

public static void GiveMeNumbers(int Max, List<int> exclude, int[] dumpNumbers)
        {
            List<int> excludeDup = new List<int>(exclude);

            for (int j = 0; j < dumpNumbers.Length; j++)
            {
                var range = Enumerable.Range(0, Max + 1).Where(i => !excludeDup.Contains(i));
                var rand = new System.Random();
                int index = rand.Next(0, Max + 1 - excludeDup.Count);
                dumpNumbers[j] = range.ElementAt(index);
                excludeDup.Add(range.ElementAt(index));
            }

        }
You would use this like: GiveMeNumbers(1000, dontIncludeThisList, dumpNumbersHere);

Language C# error on "Main" statement

$
0
0

I copied the 1st sample of code to compile the sample program & I get an error on the "Main" statement which I don't understand.   Program name is "app".  Error reads:

Error 1 Program 'C:\Users\johni_000\Documents\Visual Studio 2008\Projects\app\app\obj\Debug\app.exe' does not contain a static 'Main' method suitable for an entry point app

My statement is:

       public static void Main()

I don't understand error or how to fix it.

Can anyone help?

Icon Bar is not working again

$
0
0

I recently created a website using ASP.NET and bootstrap. At first, the icon bar was responsive when i minimize the screen; it displayed the list items on the navigation bar. But after a few days, I discovered that the icon bar is no more responding; its not displaying the navigation list items when i click the icon bar. I have included the code which i used, including the javascript code. What should I do? 

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><meta charset="utf-8"/><meta http-equiv="X-UA-Compatible" content="IE=edge"/><meta name="viewport" content="width=device-width, initial-scale=1"/><!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --><title>Joscheck Home</title><!-- Bootstrap --><link href="css/bootstrap.min.css" rel="stylesheet"/><link href="css/StyleSheet.css" rel="stylesheet" /><!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --><!-- WARNING: Respond.js doesn't work if you view the page via file:// --><!--[if lt IE 9]><script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script><script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script><![endif]--></head><body style=" background-color:#DCDCDC; background-image:url('images/Dox.png')"><form id="form1" runat="server"><div><div class="navbar navbar-default navbar-inverse navbar-fixed-top" role="navigation" style="background-color:#200662; font-family:Nunito;"><div class="container"><div class="navbar-header"><button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse" style="background-color:#200662;color:white"><span class="sr-only">Toggle Navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button><a class="navbar-brand" href="Homepage.aspx"></a></div><div class="navbar-collapse collapse"><ul class="nav navbar-nav navbar-right"><li><a href="Homepage.aspx" style="color: #FFFFFF">Home</a></li><li><a href="#" style="color: #FFFFFF">About Us</a></li><li><a href="#" style="color: #FFFFFF">Contact</a></li><li><a href="SignIn.aspx"style="color: #FFFFFF">Login/Register</a></li></ul></div></div></div></div></form><!-- jQuery (necessary for Bootstrap's JavaScript plugins) --><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script><!-- Include all compiled plugins (below), or include individual files as needed --><script src="js/bootstrap.min.js"></script></body></html>

Textbox display issue

$
0
0
How can I make a textbox for First name and another textbox for Surname be displayed horizontally and not vertically?

Response in another computer

$
0
0
My website is not responsive when i copied it to another laptop computer, what should i do to make it responsive in another laptop?

Textboxes and Labels in the middle page

$
0
0
How do I put my textboxes and labels in the middle of a webpage?

Footer Issue

$
0
0
My footer is not at the bottom of the webpage, it appears a little above my webpage what should I do?

System.Data.SqlClient.sqlException:'incorrect syntax near 'values;.

$
0
0

I want to insert data but it shows me this error.

System.Data.SqlClient.sqlException:'incorrect syntax near 'values;. 

<td class="auto-style3">&nbsp;</td>
                    <td class="auto-style5">
                        <asp:Button ID="btnReq" runat="server" OnClick="btnReq_Click" Text="Add User" />
                        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NewsConnectionString %>" InsertCommand="insert into Users valuse(@username, @password, @email)" SelectCommand="SELECT * FROM [Users]">
                            <InsertParameters>
                                <asp:ControlParameter ControlID="txtUN" Name="username" PropertyName="Text" />
                                <asp:ControlParameter ControlID="txtPW" Name="password" PropertyName="Text" />
                                <asp:ControlParameter ControlID="txtEM" Name="email" PropertyName="Text" />
                            </InsertParameters>
                        </asp:SqlDataSource>
                    </td>
                    <td>&nbsp;</td>

Using multiple background workers is ok?

$
0
0

I have 3 tabs and in each tab there is a listbox.

I have used background worker for each listbox.

Is there any other way of doing this?

Here is my code.

        public List<string> getFiles()
        {
            List<string> found = new List<string>();
            String date = DateTime.Now.ToString("dd-MM-yyyy");
            var path = Properties.Settings.Default.path;

            

            if (path == "")
            {
            
              return found;
            }
              
        
            else
            {
                try
                {
                    var files = Directory.GetFiles(path).Where(filename => filename.Contains(date)).ToList();
                   
                    
                    if (files != null)
                    {

                        foreach (var file in files)
                        {
                            using (StreamReader filess = new StreamReader(@file))
                            {
                                string line;
                                while ((line = filess.ReadLine()) != null)
                                {

                                   if (line.StartsWith("SFTP") || line.StartsWith("ERROR"))

                                        found.Add(line);

                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                    
                }
                

            }


            found.Reverse();
            return found;
        }

       private void Form1_Load(object sender, EventArgs e)
        {
           
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.DoWork += backgroundWorker1_DoWork;
            backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
            backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
            backgroundWorker1.RunWorkerAsync();

            backgroundWorker2.WorkerReportsProgress = true;
            backgroundWorker2.DoWork += backgroundWorker2_DoWork;
            backgroundWorker2.ProgressChanged += backgroundWorker2_ProgressChanged;
            backgroundWorker2.RunWorkerCompleted += backgroundWorker2_RunWorkerCompleted;
            backgroundWorker2.RunWorkerAsync();


            backgroundWorker3.WorkerReportsProgress = true;
            backgroundWorker3.DoWork += backgroundWorker3_DoWork;
            backgroundWorker3.ProgressChanged += backgroundWorker3_ProgressChanged;
            backgroundWorker3.RunWorkerCompleted += backgroundWorker3_RunWorkerCompleted;
            backgroundWorker3.RunWorkerAsync();
            
            
            notifyIcon1.Visible = true;
            notifyIcon1.Icon = SystemIcons.Exclamation;
            this.Hide();
        }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {


            List<string> result = new List<string>();

            var found = obj.getFiles();
            if (found.Count!=0)
            {

                for (int i = 0; i < found.Count; i++)
                {
                    int progress = (int)(((float)(i + 1) / found.Count) * 100);

                    result.Add(found[i]);

                    (sender as BackgroundWorker).ReportProgress(progress, found[i]);

                    System.Threading.Thread.Sleep(500);
                }



                e.Result = result;

            }
            else
            { MessageBox.Show("Data not found... "); }
        }
            

            
        

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            
            if (e.UserState != null)
           
                listBox1.Items.Add(e.UserState);
            pop.Show();
           
          
        }

        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            List<string> result1 = new List<string>();

            var found = obj.getFiles();

            foreach (var item in found)
            {
                if (item.Contains("ERROR"))
                {
                    result1.Add(item);

                    (sender as BackgroundWorker).ReportProgress(0, item);
                  
                }
                else
                    (sender as BackgroundWorker).ReportProgress(0);
                System.Threading.Thread.Sleep(1000);

            }
            e.Result = result1;
        }

        private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //Popup p = new Popup();
            //p.Close();
            if (e.UserState != null)
            {
               
                listBox2.Items.Add(e.UserState);
               pop.SetLable(e.UserState.ToString());

               pop.Hide();
                

            }
            
           
            
        }

        private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //Popup p = new Popup();
            //p.Hide();

        }

        private void backgroundWorker3_DoWork(object sender, DoWorkEventArgs e)
        {
           

            List<string> result = new List<string>();

            var found = obj.getFiles();
            if (found.Count != 0)
            {

                for (int i = 0; i < found.Count; i++)
                {
                    int progress = (int)(((float)(i + 1) / found.Count) * 100);
                    if (found[i].Contains("SFTP"))
                    {
                        result.Add(found[i]);

                        (sender as BackgroundWorker).ReportProgress(progress, found[i]);
                    }
                    System.Threading.Thread.Sleep(500);
                }



                e.Result = result;

            }
        }

        private void backgroundWorker3_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.UserState != null)
                listBox3.Items.Clear();  
            listBox3.Items.Add(e.UserState);
            
        }

Is there any other way of doing this in effective way.

C# code for object movement in cross domain.

$
0
0

I have two domain under same forest & I want to move user from one domain to another domain using c# code. With the below code I am getting error while moving users in different domain(under same domain it is working).

       DirectoryEntry eLocation = new DirectoryEntry(url, user, pass, AuthenticationTypes.ServerBind);
       DirectoryEntry nLocation = new DirectoryEntry(url1, user1, pass1, AuthenticationTypes.ServerBind);
       eLocation.MoveTo(nLocation);
       nLocation.Close();
       eLocation.Close();

error for the cross domain movement is ::

{"The user name or password is incorrect.\r\n"}

Viewing all 31927 articles
Browse latest View live


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