Quantcast
Channel: .NET Framework Class Libraries forum
Viewing all 8156 articles
Browse latest View live

Get USB drive letter from registry

$
0
0

I'm looking here to get the PID and VID for a plugged in USB drive:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\USBSTOR\Enum

Problem is that when there is more than one drive plugged in I need to know what the driver letter is for each case because I look for a file on a specific USB drive that is encrypted with the PID and VID.

For example, in the picture below, what is the driver letter for 0 and 1 (VID_0930 and VID_0951)

I want to loop through all these plugged in drives and check if the file exists on the drive, if so, get the PID and VID of that drive.

            string zeros = "";
            drives = DriveInfo.GetDrives();
            for (int i = 0; i < drives.Length; i++)
            {
                driveInfo = drives[i];
                //MessageBox.Show(driveInfo.ToString());
                //&& driveInfo.DriveType == DriveType.Removable
                //&& driveInfo.DriveType != DriveType.Unknown
                //if (driveInfo.IsReady)
               // {
                    //  MessageBox.Show(driveInfo.ToString());
                    dl = driveInfo.ToString();
               // MessageBox.Show(dl + "TechKey.txt");
                    if (File.Exists(dl + "TechKey.txt"))
                    {
                        techkey = dl + "TechKey.txt";

                        // here I need to code for if more than one drive is plugged in.

                        RegValue = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\USBSTOR\Enum", "0", 0).ToString();
                        string[] rv = RegValue.Split("\\".ToCharArray());
                        //rv[1] holds our Vid&Pid, lets go get it.
                        //Lets split the string of Vid and Pid from & inbetween
                        string[] rv2 = rv[1].Split("&".ToCharArray());
                        //Now Vid and Pid are in an array alone. Lets get their Numbers!
                        //First Vid
                        Match Vid = Regex.Match(rv2[0], @"(?<=VID_)\w*");
                        //Now Pid
                        Match Pid = Regex.Match(rv2[1], @"(?<=PID_)\w*");
                        //  Store the serial number only (excluding VID and PID)
                        string RealSerial = rv[2];

                        //Assign Original Serial
                        OriginalSerial = RealSerial;
                        //trim left characters off the serial > 16
                        if (RealSerial.Length == 16)
                        {
                            TechEnd = RealSerial;

                        }

                        if (RealSerial.Length > 16)
                        {
                            TechEnd = RealSerial.Substring(RealSerial.Length - 16);
                            //mystring.Substring(mystring.Length - 4);
                        }
                        if (RealSerial.Length < 16)
                        {
                            for (i = 0; i < (16-RealSerial.Length);i++)
                                {
                                    zeros = zeros + "0";
                                }
                            TechEnd = zeros + RealSerial;
                            //mystring.Substring(mystring.Length - 4);
                        }


                    //MessageBox.Show(RealSerial + "L: " + RealSerial.Length);
                    
                    //MessageBox.Show("Tech End" + TechEnd);

                        CompleteSerial = Vid.ToString() + Pid.ToString() + TechEnd;
                        //MessageBox.Show(CompleteSerial.ToString() + "is your complete serial for the key inside");




                    }



Run a code on Mdi Child count changed

$
0
0

Hi,

How can I run a code on MDI Child count changed?

For example..

If Mdi Child <= 0 then show the TileControl on the MainFirm (the MDI Parent).

Thanks,

Jassim

The requested operation cannot be performed on a file with a user-mapped section open

$
0
0

Hello there,

we just started to get the following error when we build/rebuild the solution with VS 2017 (The requested operation cannot be performed on a file with a user-mapped section open). we tried almost everything from updating windows, updating VS and restart the machine few time but not luck, this is happening not only for me but the all our team running Windows 10.

Any idea, suggestion would be greatly appreciated.

 Thanks


VSTS Specialist

Are there any existing gigh performance Socket libraries?

$
0
0

I am reading the sample code about the SocketAsyncEventArgs. The sample code aims at high performance by pre-allocating needed buffers. I am debugging the code to evaluate how would I inorporate the code into real projects.

Meanwhile, I would like to know if there are any existing (open source) libaries built around SocketAsyncEventArgs. If there are mature ones, I would gladly to use them to save time. Thanks for any advices.


Ignorance is blissful

HttpWebResponse.GetResponse() returning the junk Characters.

$
0
0

HttpWebResponse response = await Task.Run(() => (HttpWebResponse)request.GetResponse());

                if (response.StatusCode == HttpStatusCode.OK)
                {                    
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        responseString = reader.ReadToEnd();
                    }

                }

Please find the above code 
responseString contains a junk characters "�V���[�v �J��"

Is it because of Encoding type?

response.Characterset is "ISO-8859-1"

How to specify location of an axis' tick mark labels

$
0
0

In a Forms application I have data, bipolar in x, that I plot in a chart.  I have managed to get the y-axis to cross at 0 on the x-axis, but I can not get the labels to stay outside the chart on the left side.  I tried the following, but the labels follow the axis:

            MRGraph.ChartAreas[0].AxisX.IsMarksNextToAxis = false;
            MRGraph.ChartAreas[1].AxisX.IsMarksNextToAxis = false;
            MRGraph.ChartAreas[0].AxisX.Crossing = 0;
            MRGraph.ChartAreas[1].AxisX.Crossing = 0;
            MRGraph.ChartAreas[0].AxisY.LabelStyle.Format = "{0:#.##e+0}";
            MRGraph.ChartAreas[1].AxisY.LabelStyle.Format = "{0:#.##e+0}";

but the labels follow the axis, see figure.

How can I move the y-axis labels outside the vertical grid line at x = -88?


RSBeech

the given path's format is not supported. in MVC C# file upload

$
0
0

I've done the following code for uploading image:-

 [HttpPost]
        public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file)
        {
            // Check model state
            if (!ModelState.IsValid)
            {
                using (Db db = new Db())
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                    return View(model);
                }
            }
            // Make sure product name is unique
            using (Db db = new Db())
            {
                if (db.Products.Any(x => x.Name == model.Name))
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                    ModelState.AddModelError("", "That product name is taken!");
                    return View(model);
                }
            }
            // Declare product id
            int id;
            // Init and save productDTO
            using (Db db = new Db())
            {
                ProductDTO product = new ProductDTO();
                product.Name = model.Name;
                product.Slug = model.Name.Replace(" ", "-").ToLower();
                product.Description = model.Description;
                product.Price = model.Price;
                product.CategoryId = model.CategoryId;
                CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);
                product.CategoryName = catDTO.Name;
                db.Products.Add(product);
                db.SaveChanges();
                // Get the id
                id = product.Id;
            }
            // Set TempData message
            TempData["SM"] = "You have added a product!";
            #region Upload Image
            // Create necessary directories
            var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\")));
            var pathString1 = Path.Combine(originalDirectory.ToString(), "Products");
            var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());
            var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs");
            var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery");
            var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs");
            if (!Directory.Exists(pathString1))
                Directory.CreateDirectory(pathString1);
            if (!Directory.Exists(pathString2))
                Directory.CreateDirectory(pathString2);
            if (!Directory.Exists(pathString3))
                Directory.CreateDirectory(pathString3);
            if (!Directory.Exists(pathString4))
                Directory.CreateDirectory(pathString4);
            if (!Directory.Exists(pathString5))
                Directory.CreateDirectory(pathString5);
            // Check if a file was uploaded
            if (file != null && file.ContentLength > 0)
            {
                // Get file extension
                string ext = file.ContentType.ToLower();
                // Verify extension
                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    using (Db db = new Db())
                    {
                        model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "The image was not uploaded - wrong image extension.");
                        return View(model);
                    }
                }
                // Init image name
                string imageName = file.FileName;
                // Save image name to DTO
                using (Db db = new Db())
                {
                    ProductDTO dto = db.Products.Find(id);
                    dto.ImageName = imageName;
                    db.SaveChanges();
                }
                // Set original and thumb image paths
                var path = string.Format("{0}\\{1}", pathString2, imageName);
                var path2 = string.Format("{0}\\{1}", pathString3, imageName);
                // Save original
                file.SaveAs(path);
                // Create and save thumb
                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }
            #endregion

            // Redirect
            return RedirectToAction("AddProduct");
        }

And after running this , it shows me the error that the given path's format is not supported.

please help.

thanks

VC++.net ( C++/Cli) How to return curent Course Position in DataGridView cell

$
0
0

Hi

I am coding using C++/cli ( VC++ .Net), I have DataGridView ,user will edit the cell but in some point I will insert some info at the Course Position , so what I need to do is getting this Position so I can insert the data before he end editing .

I try this but without success :

DataGridViewTextBoxCell^ c = safe_cast<DataGridViewTextBoxCell^> (DGV1->CurrentCell);
TextBox^ control =safe_cast<TextBox^> (DGV1->EditingControl);
so anybody how to do it ?


Help please!!! (80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)). )

$
0
0

I have just created a simple web site using VB in VS2010 with reference to SourceSafe using Interop.SourceSafeTypeLib.dll, but I'm having lots of trouble on publishing it!!!

In VS everything works fine, but after publishing on the webserver I get the following error:

Retrieving the COM class factory for component with CLSID {783CD4E4-9D54-11CF-B8EE-00608CC9A71F} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)). 

HELP PLEASE!!!!

I'm in big trouble if I can't get this done fast....

 

Sorry if my english is not to good!!!


Adjusting OWNER of window using SetWindowLong is not working on Window 10 Build 1809

$
0
0

Hi 

In one of my C# application, I'm trying to set the Owner window created in one process from another process using Win32 API, For which I'm using SetWindowLong().

My use case: 

-> Primary application adjust the parent of the window created in secondary process using "SetWindowLong().

When I tried the above case, it works fine as expected with Windows 10 Build 1709. But in Windows 10 Build 1809 it fails.

Any thoughts would be helpful.

Sample:

		public static IntPtr ParentHandle
		{
			get
			{
				IntPtr hwnd = GetConsoleWindow();
				return GetParent(hwnd);
			}
			set
			{
				IntPtr hwnd = Handle;
				if (hwnd==IntPtr.Zero)
					return;

				SetParent(hwnd, value);
				int style = GetWindowLong(hwnd, GWL_STYLE);
				if (value==IntPtr.Zero)
					SetWindowLong(hwnd, GWL_STYLE, (style &~ WS_CHILD) | WS_OVERLAPPEDWINDOW);
				else
				//	SetWindowLong(hwnd, GWL_STYLE, (style | WS_CHILD) &~ WS_OVERLAPPEDWINDOW); 
					SetWindowLong( hwnd, GWL_STYLE, style & ~WS_OVERLAPPEDWINDOW );
				SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
			}
		}

Denial of Service - The call to ReadToEnd() might allow an attacker to crash the program or otherwise make it unavailable to legitimate users.

$
0
0

Hi All,

I have got this error under security scanning with ReadToEnd() method. Can anyone suggest how can I fix this issue?

ManagementEventWatcher Gets Stopped as soon as Start() called

$
0
0

Hi,

As soon as I started the ManagementEventWatcher for Printer Jobs event, I am getting the Stop() event gets called immediately.

Kindly suggest me resolve this issue.

Here is my code,

public void StartPrintWatcher()
        {            
            _printEventWatcher = new System.Management.ManagementEventWatcher();
            _printEventWatcher.Query = new System.Management.EventQuery("SELECT * FROM __InstanceCreationEvent WITHIN " + 1 + " WHERE TargetInstance ISA \"Win32_PrintJob\"");

            string hostName = Dns.GetHostName();
            this._printEventWatcher.Scope = new System.Management.ManagementScope("\\\\" + hostName + "\\root\\CIMV2");
            _printEventWatcher.EventArrived += new EventArrivedEventHandler(this.Arrived);
            _printEventWatcher.Stopped += new StoppedEventHandler(PrintEventWatcher_Stopped);
            _printEventWatcher.Start();
        }

protected void PrintEventWatcher_Stopped(object sender, StoppedEventArgs e)
        {
            try
            {
                logger.Info("PrintEventWatcher_Stopped...");
                ((ManagementEventWatcher)sender).Dispose();
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message); balObj.AddtoErrorLogTable(ex.ToString());
            }
        }

How to consume WSDL service from code?

How to split string with comma intro two strings?

$
0
0

Hi,

I have this string:

"25.2647474540001,55.3115426040001"

which represents latitude and longitude

How can I split it to have the address_latitude and address_longitude individually?

Thanks,

Jassim

.NET Core 2.1 MVC application to mark attendance

$
0
0

Hello!

I'm posting a bunch of details to be as clear as I can be so bear with me.

I've recently started learning .NET Core & MVC by following some courses on Microsoft Virtual Academy & PluralSight. At the same time I'm using what I'm learning to create an application toCapture Attendance.

I have googled and found a bunch of awsome examples from github, however I have decied to build my own to make it suit my requirements and to learn this technology more!

The name of the application is quite descriptive, I need an application where I can create MembersEvents. Then at any time I would like to be able to create an Event containing all of my Membersand mark these as Present or Absent.

A colleague helped me design the database using EntityFramework, take a look at my models and the tables created based on them:

public class Members
{
    public int Id { get; set; }
    [DataType(DataType.Text)]
    public string FirstName { get; set; }
    [DataType(DataType.Text)]
    public string LastName { get; set; }
    [DataType(DataType.Text)]
    public string FullName { get; set; }
    [DataType(DataType.Date)]
    public DateTime DateOfBirth { get; set; }
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
    [DataType(DataType.PhoneNumber)]
    public string TelephoneNumber { get; set; }
    public List<MemberToEvents> MemberToEvents { get; set; }
}

public class Events
{
    public int Id { get; set; }
    [DataType(DataType.Date)]
    public DateTime EventDate { get; set; }
    public List<MemberToEvents> MemberToEvents { get; set; }
}
public class MemberToEvents
{
    public int Id { get; set; }
    public bool Status { get; set; }
    public Events Event { get; set; }
    public Members Member { get; set; }
}

After scaffolding and deploying I get my tables created exactly as planned:

  • dbo.MemberToEvents
  • dbo.Events
  • dbo.Members

So far so good, I can now create/view/edit/delete Members and Events.

Now, using some View(?), I'm looking for a way to capture attendance status for all my members for a specific Event (date) and save it to my MemberToEvents table.

My little knowledge of this technology is not helping to figure out a solution. Could you please help?
I'm not posting my not working code because I know it's far from being usable.

Thanks in advance!


ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 and Cipher Suite (C#)

$
0
0

Hello,

I should to connect a Server per HttpWebRequest with one of TLS Cipher Suites (possible ECDHE-RSA-AES256-GCM-SHA384)

If I use under Windows Server 2016 Standard with MS Framework 4.6.1 following command (C#):

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; 

is one of Cipher Suites already included?

If no, what should I do? How can I expand the code below to achive this goal?

Thanks

     private static String sendRequest(Uri url, NameValueCollection nvc)
        {
            CookieContainer cookieJar = new CookieContainer();
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                   | SecurityProtocolType.Tls11
                   | SecurityProtocolType.Tls12
                   | SecurityProtocolType.Ssl3;

            ServicePointManager.Expect100Continue = true;

            HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create(url.ToString());

            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

            HttpWReq.ProtocolVersion = HttpVersion.Version10;
            HttpWReq.Timeout = Timeout.Infinite;
            HttpWReq.ReadWriteTimeout = Timeout.Infinite;


            HttpWReq.CookieContainer = cookieJar;
            HttpWReq.Method = "POST";
            HttpWReq.Accept = "*/*";
            // req3.Headers.Add("Pragma", "no-cache");
            // req3.Headers.Add("Accept-Language", "en-gb");
            HttpWReq.AllowAutoRedirect = true;
            HttpWReq.KeepAlive = true;
            HttpWReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
            HttpWReq.ContentType = "application/x-www-form-urlencoded";
            HttpWReq.ProtocolVersion = HttpVersion.Version10;

            var sbPostData = new StringBuilder();

            sbPostData = CreateParameterString(nvc);
            var parameterString = (System.Text.Encoding.GetEncoding(iWinCodePage)).GetBytes(sbPostData.ToString());

            if (sbPostData.ToString().Length > 0)
            {
                HttpWReq.ContentLength = sbPostData.ToString().Length;
            }
            String responseString = "";

            if (sbPostData.ToString().Length > 0)
            {
                Stream requestStream = HttpWReq.GetRequestStream();
                requestStream.Write(parameterString, 0, parameterString.Length);
                requestStream.Close();
            }

            HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();

            StringBuilder response = new StringBuilder();

            using (StreamReader sr = new StreamReader(HttpWResp.GetResponseStream(), System.Text.Encoding.GetEncoding(iWinCodePage), true)) 
            {
				response = sr.ReadToEnd();
            }

            responseString = response.ToString();

            return responseString;

        }

Unable to cast object of type 'FileStreamDeleteOnClose' to type 'System.IO.MemoryStream'.

$
0
0
this is my code to display a report in pdf and am gettin the error while displaying. please help
        ReportDocument rptdoc = new ReportDocument();
        rptdoc.Load(Server.MapPath("DatDebutContrat2.rpt"));
        //permet d'afficher le crystalreport en PDF
        MemoryStream oStream;
        oStream = (MemoryStream)rptdoc.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=DebutContrat Contrat.pdf");
        Response.ContentType = "application/pdf";//extension en pdf
        System.IO.StringWriter wrt = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htwrt = new System.Web.UI.HtmlTextWriter(wrt);
        Response.Write(wrt.ToString());
        Response.Flush();
        Response.Buffer = true;
        Response.BinaryWrite(oStream.ToArray());
        Response.End();
        rptdoc.Dispose();
        rptdoc.Close();

Windows form application in 64 bit process

$
0
0

Hello,

Actually we have created one windows form application in .net 4.7 and built in Any CPU mode. So, if its running in 64 bit OS. It will run as 64 bit application.

My question is what is the maximum memory it can use in 64 bit process?

My installed RAM is 6GB. Please help on this.

Best Regards,

Hari


click "Proposed As Answer by" if this post solves your problem or "Vote As Helpful" if a post has been useful to you Happy Programming! Hari

What are benefits of creating migrations from the beginning of the project using EF Core?

$
0
0
I am setting up a new ASP.NET core mvc project with EF Core. Now, When I read the docs for help in implementation, it always says to create a migration file (.cs) and then update the database with the help of that file. But, If have to create a separate class and then update the database instead of the usual update database commands, wouldn't it kill the purpose of setting of db easily using EF Core? I mean simply running update database command will also do the same thing but without the additional step of creating a migration file. So my question is, while setting up a project from the scratch, is it necessary to create a migration file of every single step i.e while initial creation of database with basic table and schemas? if so what are the advantages?

ms forum help

Create certificates using CertificateRequest and import to X509Store with private key

$
0
0

I would like to generate certificates with private key's in my application and import them into the X509Store. I've so far managed to generate the certificates with the private key using the new CertificateRequest class. But if I just import them directly into the X509Store they don't have the private key. The only way to import them including the private key I found so far is to export and import them again using a password and the PersistKeySet flag. Here is an example:

byte[] certRaw = myGeneratedCert.Export(X509ContentType.Pfx, "MySecretPassword");

X509Certificate2 certThatImportsWithPK = new X509Certificate2(certRaw, "MySecretPassword", X509KeyStorageFlags.PersistKeySet);

using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
    store.Open(OpenFlags.ReadWrite);
    store.Add(certThatImportsWithPK);
}

Is there a better way to do this with certificates that are generated using the CertificateRequest class?

Viewing all 8156 articles
Browse latest View live