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

LdapException.ServerErrorMessage and ComponentModel.Win32Exception.NativeErrorCode values

$
0
0
  • LdapException.ServerErrorMessage

What setting / condition "decides" weather or not the  LdapException.ServerErrorMessage  is populated with the correct value when an account is set to MustChangePassword.

8009030C: LdapErr: DSID-0C0904D0, comment: AcceptSecurityContext error, data 773, v1db0

instead of

comment: AcceptSecurityContext error, data 0

  • ComponentModel.Win32Exception

when using LogonUser from advapi32.dll and catching the ComponentModel.Win32Exception

the NativeErrorCode property sometimes is blank event when the account is set to user must change passeord.

Background:

the context is always within a Enterprise admin user. ( IE the executable / windows service is launched under the Ent. Admin user ) 

the application I am working on needs to validate user logons ( and return the correct reason why a failure occurs ( locked, change password disabled etc) in a multi forest environment with full trusts between the forest roots. some of the domains are 2003 r2 some are 2008 r2 and some are 2012.    I am noticing the lack of reasons coming back when dealing with the 2003 r2 AD machines.     btw if the account is NOT set to change password or is locked I am always able to validate the positives )

 


Accessing network drives

$
0
0

I'm sorry, but can't find a better section to post this in. Please move to a more appropriate section if needed.

I have (written) a windows service that can either run as a service or as a console app (by passing a command line argument). The program runs on computer A and accesses a directory on computer B and a directory on computer C.

When I run the application version, the program works as expected and can access both remote directories. If I run the program as a service, it can only access the directory on computer B and I get a UnAuthorized Access exception for computer C.

I'm accessing the drive by IP address (e.g \\192.168.13.55\somefolder and 192.168.33.34\otherfolder) and the credentials for all computers are different. I can also access the directories using the above IP address from Windows Explorer.

The service runs with LocalSystem privilege and a valid username/password is specified on system A (Adminstrator credentials for computer A) for the service in the service manager.

To make matters worse, if I run the service version on another computer (Z), I can't access any of the remote directories while the console version again works happily as expected. Another service on this computer accessing one of those directories still works as expected.

I'm now trying to understand how credentials are used when remote directories are accessed.Can somebody point me to an article how it all works? If somebody has a solution based on the above information, it would also be appreciated ;-)

Thanks in advance.

Note:

I usually 'code' the service installer using the VisualStudio drag-n-drop functionality. This service differs in that I created it from scratch (read: copied it from somewhere on the web). The other difference with the other services that I have written is that this one attempts to access two different computers while the others only access a remote directory on one computer.

Just in case I did something wrong with the installer, the code (I did compare it to the designer file generated by VisualStudio 2012 for another service and did not find relevant differences).

using System;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
namespace WAC
{
    [RunInstaller(true)]
    public class WACServiceInstaller : Installer
    {
        /// <summary>
        /// Public Constructor for WindowsServiceInstaller.
        /// - Put all of your Initialization code here.
        /// </summary>
        public WACServiceInstaller()
        {
            ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();
            ServiceInstaller serviceInstaller = new ServiceInstaller();

            //# Service Account Information
            serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
            serviceProcessInstaller.Username = null;
            serviceProcessInstaller.Password = null;

            //# Service Information
            serviceInstaller.DisplayName = "WAC";
            serviceInstaller.Description = "Checks if scheduled assets are available";
            serviceInstaller.StartType = ServiceStartMode.Manual;

            //# This must be identical to the WindowsService.ServiceBase name
            //# set in the constructor of WindowsService.cs
            serviceInstaller.ServiceName = "WAC Service";

            this.Installers.Add(serviceProcessInstaller);
            this.Installers.Add(serviceInstaller);
        }
    }
}
Note that some comments still exist from the original source.



is multi row insert using an array supported with .NET C#?

$
0
0
Does .net Framework 4.6 support this type of multi row insert, with values provided via an array:

"insert into table1 values(?) for 2 rows";

System.OutofMemoryException while reading from TCP Server

$
0
0

Hello,

I am creating TCP Client application and when I am trying to read data from tcp server it throws exception.  Below is my code please help me where I am getting wrong

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;

namespace TCPClient
{
    public partial class Form1 : Form
    {
        int i;
        StreamWriter streamWriter;
        StreamReader streamReader;
        TcpClient client; // Creates a TCP Client
        NetworkStream stream; //Creats a NetworkStream (used for sending and receiving data)
        byte[] datalength = new byte[4]; // creates a new byte with length 4 ( used for receivng data's lenght)
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                client = new TcpClient("192.168.1.147", 747); //Trys to Connect
               ClientReceive(); //Starts Receiving When Connected
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message); // Error handler :D
            }
        }
        public void ClientReceive()
        {

            stream = client.GetStream(); //Gets The Stream of The Connection
            new Thread(() => // Thread (like Timer)
            {
                while ((i = stream.Read(datalength, 0, 4)) != 0)//Keeps Trying to Receive the Size of the Message or Data
                {
                    // how to make a byte E.X byte[] examlpe = new byte[the size of the byte here] , i used BitConverter.ToInt32(datalength,0) cuz i received the length of the data in byte called datalength :D
                    byte[] data = new byte[BitConverter.ToInt32(datalength, 0)]; // Creates a Byte for the data to be Received On
                    stream.Read(data, 0, data.Length); //Receives The Real Data not the Size
                    this.Invoke((MethodInvoker)delegate // To Write the Received data
                    {
                        txtLog.Text += System.Environment.NewLine + "Server : " + Encoding.Default.GetString(data); // Encoding.Default.GetString(data); Converts Bytes Received to String
                    });
                }
            }).Start(); // Start the Thread
        }

        public void ClientSend(string msg)
        {
            stream = client.GetStream(); //Gets The Stream of The Connection
            byte[] data; // creates a new byte without mentioning the size of it cuz its a byte used for sending
            data = Encoding.Default.GetBytes(msg); // put the msg in the byte ( it automaticly uses the size of the msg )
            int length = data.Length; // Gets the length of the byte data
            byte[] datalength = new byte[4]; // Creates a new byte with length of 4
            datalength = BitConverter.GetBytes(length); //put the length in a byte to send it
            stream.Write(datalength, 0, 4); // sends the data's length
            stream.Write(data, 0, data.Length); //Sends the real data
        }

        private void btnSend_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (client.Connected) // if the client is connected
            {
                ClientSend(textBox1.Text); // uses the Function ClientSend and the msg as txtSend.Text
            }
        }

    }
}

Error in arrays

$
0
0

int x, temp;
            int input = 0;
            int[] num = new int[10];

            // ******

            Console.WriteLine("Please input ten numbers: ");
            for (x = 0; x < 10; x++)
            {
                for (x = 0; x < 10; x++)
                {
                    Console.Write("{0 }", x);
                    x = int.Parse(Console.ReadLine());
                }
            }

            // ******
            Console.Write("\n\nlowest to highest");
            for (int a = 0; a < 10; a++)
            {
                for (int o = 0; o < 9; o++)
                {
                    temp = input[a + 1];
                    input[a] = temp;
                }
            }

            for (x = 0; x < 10; x++)
            {
                for (x = 0; x < 10; x++)
                {
                    Console.Write("{0 }", x);
                    x = int.Parse(Console.ReadLine());
                }
            }


            // ******
            Console.Write("\n\nhighest to lowest");
            for (int b = 0; b < 10; b++)
            {
                for (int p = 0; p > 9; p++)
                {
                    temp = input[b + 1];
                    input[b] = temp;
                    b = int.Parse(Console.ReadLine());
                }
            }

            for (x = 0; x < 10; x++)
            {
                for (x = 0; x < 10; x++)
                {
                    Console.Write("{0 }", x);
                    x = int.Parse(Console.ReadLine());
                }
            }

            Console.ReadLine();

Hi guys, little help for a friend? Why does it tell me that "cannot apply indexing [] to an expression of type int" maybe i have an error to one of my variables. Well, I put my variables the right way. But, the reason is when I try to debug it. There's still this error. Need professional help. Thanks.

Conversion Probelm

$
0
0

Hi,

 I have an asp.net application with C#,If I Convert the below,

Convert.ToInt32("2CADD",16)//it is converting fine  and not throw any error.

But if Convert.ToInt32("2CADDStation",16)//it is throwing an error. how can I convert?.

Thanks ,

Dileep

Regex to validate Windows product key

$
0
0

Hello,

I need to write regex to validate Windows product key. 

Please help me on this.

thanks in advance.

Mahadevan.G

Expose Object arrays/list throughout app - best practice

$
0
0

I am trying to redesign a desktop application from an old C++ app to C# and have a need to create a class object with multiple instances of the class (1 instance defining a specific manufacturing work center) and have this array/list/collection exposed throughout the application.

Being relatively new to C#, I am looking at best practices in doing this. I have read many posts on the evils of static classes, singletons, and global lists and that gets me wondering, what is the best practice?

In a nutshell, I have a main form class that will reference the object class. I can populate and reference the class no problem, but I really need to get a list of objects defining each of my work centers and have these exposed throughout the application.

The application run in a while(true) cycle so I am trying to avoid getting the data from the database on every iteration of the cycle.

Any suggestions or references to a best practice would be most helpful.


Dynamic xml Serialization

$
0
0

I am trying to generate an xml by serializing and facing some issues. Thereis a part of xml which is dynamic. the section "person" is dynamic i.e the sub sections
(name and age)under person can increase or decrease. I am able to serialie the class with static value( with single person name and age) but when getting multiple 
values then I am not able to handle that.All the values are fetched from database and every name and age is store as a distinct row in database.So if I have 2 names and age then it will be stored
as 2 distinct rows in database. I tried to create a loop(on basis of number of rows) but not able understand how to incorporate the dynamic section to rest of xml part.

Can someone help on this?

create table persondetails(name varchar(20),age int)
insert into persondetails(name,age)
select 'Dann',21
union all
select 'Scott',23
union all
Select 'Allen',24

Desired output XML:

<details>
 <description>Some description</description>
 <hobby> Anything</hobby>

<person>
   <name>Dann</name>
   <age>21</age>
   <name>Scott</name>
   <age>23</name>
</person>

</details>

   

asp.net gridview "paging"

$
0
0

hello everyone,

let me explain what im doing. i have a situation where i have a gridview with paged data, and each page has a diffrent amount of rows. the default paging feature only allows one value for the page size for all the pages. 

my solution to this problem was keep records of how long each page is in a table and use the visible property to hide rows that shouldnt be seen and show rows that need to be viewed.

here is my code

DataView ddl = (DataView)Dropdowndates.Select(DataSourceSelectArguments.Empty);
        int last = 0;
        int start = 0;
        int end = 0;

        for (int i = 0; i < ddl.Count; i++)
        {      //adds the amount of rows from each month to a start index
            last += Int32.Parse(ddl.Table.Rows[i][3].ToString());

        }
        for (int i = 0; i < DropDownList1.SelectedIndex; i++)
        {      //adds the amount of rows from each month to a start index
            start += Int32.Parse(ddl.Table.Rows[i][3].ToString());
            if (i == DropDownList1.SelectedIndex)
            {
                start += 1;
            }
        }
        for (int i = 0; i < DropDownList1.SelectedIndex + 1; i++)
        {      //adds the amount of rows from each month to a start index
            end += Int32.Parse(ddl.Table.Rows[i][3].ToString());

        }

        for (int i = 0; i < last; i++)
        {
            grid.Rows[i].Visible = false;
        }

        for (int i = 0; i < last; i++)
        {
            if ((Int32.Parse(grid.Rows[i].Cells[1].Text) > start) && (Int32.Parse(grid.Rows[i].Cells[1].Text) <= end))
            {
                grid.Rows[i].Visible = true;
            }
        }

this works great except when i press the edit or sort buttons then i have to re run my "paging" code

my paging code gets run everytime someone selects what page they want to view from a dropdown box. 

so in order for it to work you have re selcet the page you want to view whenever you sort or try to edit.

i tried calling my "paging" code from Page_Load but that just caused all sorts of weird problems.

any ideas for better solutions or how to fix my solution?? 

thank you!!

Change button colour

$
0
0

Hello I'm new to C#, I don't know if this is the correct forum but.

I want to change the colour of a button I can change in in Visual Studios Properties however this leaves a blue border around the first button and a white border around other buttons. Also i would like to add some MouseEnter and MouseLeave effect but I am unsure how to could someone please help?

You can see a picture of my problem here: http://s20.postimg.org/9t1m8c76l/Button.jpg

Serialize the complex json string

$
0
0
I have a json string.
{"photos":[
      {"id":103389,"sol":1000,"camera":{"id":16,"name":"NAVCAM","rover_id":6,"full_name":"Navigation Camera"
         },"img_src":"http://mars.jpl.nasa.gov/msl-raw-images/proj/msl/redops/ods/surface/sol/01000/opgs/edr/ncam/NLB_486264973EDR_S0481570NCAM00546M_.JPG","earth_date":"2015-05-30","rover":{"id":5,"name":"Curiosity","landing_date":"2012-08-06","max_sol":1242,"max_date":"2016-02-03","total_photos":234449,"cameras":[
               {"name":"FHAZ","full_name":"Front Hazard Avoidance Camera"
               },
               {"name":"NAVCAM","full_name":"Navigation Camera"
               },
               {"name":"MAST","full_name":"Mast Camera"
               },
               {"name":"CHEMCAM","full_name":"Chemistry and Camera Complex"
               },
               {"name":"MAHLI","full_name":"Mars Hand Lens Imager"
               },
               {"name":"MARDI","full_name":"Mars Descent Imager"
               },
               {"name":"RHAZ","full_name":"Rear Hazard Avoidance Camera"
               }
            ]
         }
      },
      {"id":103388,"sol":1000,"camera":{"id":16,"name":"NAVCAM","rover_id":6,"full_name":"Navigation Camera"
         },"img_src":"http://mars.jpl.nasa.gov/msl-raw-images/proj/msl/redops/ods/surface/sol/01000/opgs/edr/ncam/NLB_486265046EDR_S0481570NCAM00546M_.JPG","earth_date":"2015-05-30","rover":{"id":5,"name":"Curiosity","landing_date":"2012-08-06","max_sol":1242,"max_date":"2016-02-03","total_photos":234449,"cameras":[
               {"name":"FHAZ","full_name":"Front Hazard Avoidance Camera"
               },
               {"name":"NAVCAM","full_name":"Navigation Camera"
               },
               {"name":"MAST","full_name":"Mast Camera"
               },
               {"name":"CHEMCAM","full_name":"Chemistry and Camera Complex"
               },
               {"name":"MAHLI","full_name":"Mars Hand Lens Imager"
               },
               {"name":"MARDI","full_name":"Mars Descent Imager"
               },
               {"name":"RHAZ","full_name":"Rear Hazard Avoidance Camera"
               }
            ]
         }
      }
I want to get all img_src. I know it is the directory structure but it is hard to get it. The partial code.
 JavaScriptSerializer ser = new JavaScriptSerializer();
                var data = ser.Deserialize<Dictionary<string,object>>(json);
                foreach (var item in data)
                {
                    var photos = (ArrayList)item.Value;
                    for (int i = 0; i < photos.Count; i++)
                    {
                        var element = photos[i];
                       // need another dictionary??
                    }
                }
Thanks.



How can call function when webBrowser Document is changed?

$
0
0
        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            webBrowser1.Document.GetElementById("event-more-view-3813947").InvokeMember("click");
        }


        private void button2_Click(object sender, EventArgs e)
        {
            string str = webBrowser1.Document.Body.Parent.OuterHtml;
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(str);
            if (doc != null)
            {
                var Text2 = doc.DocumentNode.SelectNodes("//tr[@class='market-details-3813947']");
                foreach (var c in Text2)
                {
                    textBox1.Text += c.InnerHtml;
                }
            }
        }

I want to get HTML page from "tr". But at first, I have to click on an element to make the script run, after that the table with "tr" that I need, is shown and I can get my text...
The problem is, that I want to do it step by step, not buy pressing 2 buttons.

If I call code inside of button2_Click() from webBrowser1_DocumentCompleted, it doesn't work, because Browser need some time to run the script. And Sleep(time), doesn't help. The Browser getting freez for some time and after that, script runs.

How can I solve this problem?

Display image in pdf

$
0
0

hi

i want to display company logo in print pdf format.

i am working on windows form application using c#.net and i want to display logo image using html image tag.

please see may below code:

 <img src=\"C:\C# Projects\Fahinds\Fahinds\images\honda.jpg\" height=\"95\" width=\"120\">

using above code i am not able to get logo on pdf file.

my image is located in my project local drive.

please help to resolve my this issue ASAP.


How to Use sum function in access

$
0
0

Hi,

I have product_order table in that have price column.

I want to calculate total price and display on label.

see below my query and error screen shot.

SELECT Sum(price) AS [Total Price] FROM product_order; 

cannot have memo,ole or hyperlink object in aggregate argument (price).

i am getting above error please help.

how to do sum of total price column.



Sort a String array Value

$
0
0

Hi,

I have asp.net 4.5 application with C#. In My code I having an arry. That array contains html string value. The Html sting avalue in array display as below now,

<span obj_type="prod" _ProdId="111-403"> //array(0)
<span obj_type="prod" _ProdId="111-401">//array(1)
<span obj_type="prod" _ProdId="111-404">//array(2)
<span obj_type="prod" _ProdId="111-402">//array(3)

Need to sort the abobe array values based on ProdId.How can I achive for sort this?.

Thanks & Regards

Dileep

unzip password protected .zip files in directory

$
0
0

Hello,
I have the password for each of the .zip files.
How is it possible to loop through a directory where these password protected zip files are sitting?

Thanks

Adding Progress bar to ExportToExcel project

$
0
0
public void ExportToExcel(DataGridView gridviewID, string excelFilename)
        {

            Microsoft.Office.Interop.Excel.Application objexcelapp = new Microsoft.Office.Interop.Excel.Application();
            objexcelapp.Application.Workbooks.Add(Type.Missing);
            objexcelapp.Columns.ColumnWidth = 25;
            for (int i = 1; i < gridviewID.Columns.Count + 1; i++)
            {
                objexcelapp.Cells[1, i] = gridviewID.Columns[i - 1].HeaderText;
            }
            /*For storing Each row and column value to excel sheet*/
            for (int i = 0; i < gridviewID.Rows.Count; i++)
            {
                for (int j = 0; j < gridviewID.Columns.Count; j++)
                {
                    if (gridviewID.Rows[i].Cells[j].Value != null)
                    {
                        objexcelapp.Cells[i + 2, j + 1] = gridviewID.Rows[i].Cells[j].Value.ToString();
                    }
                }
            }
            DialogResult dialog = MessageBox.Show("Your excel file exported successfully at C:\\GetIODB\\" + excelFilename + ".xlsx", "Excel Generate", MessageBoxButtons.OK);
            objexcelapp.ActiveWorkbook.SaveCopyAs("C:\\GetIODB\\" + excelFilename + ".xlsx");
            objexcelapp.ActiveWorkbook.Saved = true;
            if (dialog == DialogResult.OK)
            {
                Process.Start(@"C:\GetIODB");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
                ExportToExcel(IOdbTrg, "EIreport");
            }
        }
    }

Hello Guys,

I'm going to adding progress bar to my Export To Excel project. Above code are current works just fine, but I just didn't know when that exporting to excel process going to done and popup the message box. How to edit my code to add progress bar?

user input skips, and closing application.

$
0
0

Hey there!

I've been building a console application, that works a bit like a game.

I want to make a user input, that checks with room they want to visit.

The problem is, when the game is at the point when the user can input a number, it skips that area and closes the app.

This is my code:

namespace GoldFinder
{
    class Program
    {

        //INT
        static int gold = 0;
        static int table = 1;


        static void Main(string[] args)
        {

            Console.WriteLine("---------------------------------------------------");
            Console.WriteLine("---------------GOLDFINDER 1.0 BETA-----------------");
            Console.WriteLine("---------------------------------------------------");
            Console.WriteLine("--------------Press any key to start---------------");
            Console.WriteLine("---------------------------------------------------");

            Console.ReadKey();

            Lobby();
        }

        static void Lobby()
        {
            Console.Clear();

            Console.WriteLine("You are in the lobby, where do you want to go?");
            Console.WriteLine("Go to: ");
            Console.Write("[1]Bathroom, [2]Kitchen, [3]Bedroom, [3]Street.");

            string in_ = Console.ReadLine();

            int go = Convert.ToInt32(in_);

            Boolean good = false;

            while (good == false)
            {

                if (go == 1)
                {

                    Bathroom();

                    good = true;

                }
                else
                {

                    Console.WriteLine("Wrong data, type a correct number.");

                }

            }
        }
    }
}

If anyone can solve my problem, feel free to awnser.

p.s. I know that I don't got "bathroom()". I want to add it later.

Storing sets of 2 strings in a List in Properties.Settings.Default.MyList ??

$
0
0

I want to store some machine names and MacAddresses in the Properties.Settings.Default.MyList

I think I have to choose ArrayList as Type in the Settings.Settings-window, but how do I enter the initial values in the Value-column.

Viewing all 31927 articles
Browse latest View live


Latest Images

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