Update Registry or Environment Variable on Remote Machine in C#

Environment variable are available in “HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment” in registry. By making a new entry in registry we can set environment variable on remote machine.
Here is the code to update the registry or set environment variable of the remote machine.

void UpdateRegistryOnRemotemachine(string RemoteMachineName)
        //retrieve Key information
        RegistryKey environmentKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "\\\\" + RemoteMachineName).OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true);

        if (environmentKey != null)
            RegistryKey envRegistry = environmentKey;
            envRegistry.SetValue(txtVariableName.Text.Trim(), txtVariableValue.Text.Trim());
    catch (Exception Ex)
        string ErrorMsg = "\r\nError:\t" + Ex.Message;
        ErrorMsg += "\r\nStack:\t" + Ex.StackTrace;


To run above code successfully following settings must be done on remote machine –
1. “Remote Registry” service should be start on remote machine.
– To start “Remote Registry” service, type services.msc on run prompt and search for “Remote Registry”. Right click on “Remote Registry” service and set it to automatic and start it.

2. Window Firewall should be configure or should be off on remote machine.
3. A user (which will access registry of remote machine) must be added with administrator privileges on remote machine. To add user with administrator privileges do following thing
– Right click on MyComputer and click on manage.
– Expand Local users and groups
– Double click on groups and then double click on administrator group.
– Add user (which will access registry of remote machine from another machine) in this group.

Now by doing all above setting that user can update registry of remote machine.

Posted in Uncategorized. 3 Comments »

Get unread mail count of Gmail in C#

Following code demonstrate that how to get count of unread mail of Gmail account in C#. Gmail provides link “https://mail.google.com/mail/feed/atom” to access unread mail by user authentication.

Following is code description.
First we declare a structure which will contain information of unread mails –

    struct UnreadMails
        public string From { get; set; }
        public string Subject { get; set; }
        public DateTime MailModify { get; set; }

Now following function will return collection of unread mail using authentication –

        Collection<UnreadMails> GetNewMails()
            WebRequest webGmailRequest = WebRequest.Create(@"https://mail.google.com/mail/feed/atom");
            webGmailRequest.PreAuthenticate = true;

            NetworkCredential loginCredentials = new NetworkCredential(txtUserName.Text.Trim(), txtUserPassword.Text.Trim());
            webGmailRequest.Credentials = loginCredentials;

            WebResponse webGmailResponse = webGmailRequest.GetResponse();
            Stream strmUnreadMailInfo = webGmailResponse.GetResponseStream();

            StringBuilder sbUnreadMailInfo = new StringBuilder(); byte[] buffer = new byte[8192]; int byteCount = 0;

            while ((byteCount = strmUnreadMailInfo.Read(buffer, 0, buffer.Length)) > 0)
                sbUnreadMailInfo.Append(System.Text.Encoding.ASCII.GetString(buffer, 0, byteCount));

            XmlDocument UnreadMailXmlDoc = new XmlDocument();
            XmlNodeList UnreadMailEntries = UnreadMailXmlDoc.GetElementsByTagName("entry");

            UnreadMails oUnreadMails = new UnreadMails();
            Collection<UnreadMails> clUnreadMails = new Collection<UnreadMails>();

            for (int _i = 0; _i < UnreadMailEntries.Count; ++_i)
                oUnreadMails.Subject = (UnreadMailEntries[_i]["title"]).InnerText;
                oUnreadMails.From = (UnreadMailEntries[_i]["author"])["name"].InnerText + " <" + (UnreadMailEntries[_i]["author"])["email"].InnerText + ">";
                oUnreadMails.MailModify = DateTime.Parse((UnreadMailEntries[_i]["modified"]).InnerText);
            return clUnreadMails;

Now call above function on button click to get count of unread mail. There is also a check in this function that if any unread mail count once then it will not count as new unread mail –

        DateTime LastCheck = DateTime.MinValue;
        private void btnLogin_Click(object sender, EventArgs e)
            int NewUnreadMail = 0;
            DateTime LastUnreadMailDate = DateTime.MinValue;
            Collection<UnreadMails> clUnreadMails = GetNewMails();
            for (int i = 0; i < clUnreadMails.Count; i++)
                if (clUnreadMails[i].MailModify > LastCheck)
                if (clUnreadMails[i].MailModify > LastUnreadMailDate)
                    LastUnreadMailDate = clUnreadMails[i].MailModify;
            LastCheck = LastUnreadMailDate;
            lblTotalUnreadMailCount.Text = "Total Unread Mail Count -  "+ clUnreadMails.Count.ToString();
            lblNewUnreadMailCount.Text = "New Unread Mail Count -  " + NewUnreadMail.ToString();

Following is a image of UI of form –

Posted in Uncategorized. 8 Comments »

Move window form without Titlebar in C#

I am going to describe two method of moving Window Form without title bar.

I Method – Using Windows API
Add following code in your .cs file

public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;

public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
public static extern bool ReleaseCapture();

Now write following code on MouseMove event of that control on which window form should move –

private void panel1_MouseMove(object sender, MouseEventArgs e)
        if (e.Button == MouseButtons.Left)
                SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);

II Method : Using C# Code
Add following variables in your .cs file.

private bool mouseIsDown = false;
private Point firstPoint;

Now handle MouseMove, MouseUp, MouseDown event of that window control on which window form should move.
Code is as follow –

private void panel1_MouseMove(object sender, MouseEventArgs e)
            if (mouseIsDown)
                // Get the difference between the two points
                int xDiff = firstPoint.X - e.Location.X;
                int yDiff = firstPoint.Y - e.Location.Y;

                // Set the new point
                int x = this.Location.X - xDiff;
                int y = this.Location.Y - yDiff;
                this.Location = new Point(x, y);

        private void panel1_MouseDown_1(object sender, MouseEventArgs e)
            firstPoint = e.Location;
            mouseIsDown = true;

        private void panel1_MouseUp(object sender, MouseEventArgs e)
            mouseIsDown = false;

Note: Drawback of second method is, when cursor will move below taskbar then window form will also go below taskbar.

Posted in Uncategorized. 5 Comments »

Share With You


I am sharing list of some .Net interview questions. Click here to Download.

Above attachment has question list only. You can ask these questions to yourself and can evaluate yourself that where you stand in .Net technologies.

I am running this thread to share knowledge, learning materials with all of you and as well as me also.

Please send your feedback, your learning or any suggestion on sharing knowledge with each other.

Insert & Keyword in XML or Include & in XML

To include ‘&’ in XML. Following should be use –

Use &app; instead of &

Example –

Suppose if you want to write Right&Left in XML file, then just replace & with &app;

Means you have to write Right&app;Left in XML file.

Posted in Uncategorized. Leave a Comment »

Declare Shared Variable in VC++

Shared Variable – Shared variables are those variables which can be shared in multiple instance of the same application. Suppose we are running three instance of an exe, then the value of shared variable will be same in all three instances. If any instance change the value of shared variable then it will be reflect in all instance.

In short shared variable is same as static variable, the only difference is that static variable contain same value for all instance of class and shared variable contains same value for all instance of application.

To declare shared variable in VC++, following code can be use in .cpp file

// shared data
#pragma data_seg(“.SHARED”)
int IsHomePageSet = -1;
#pragma data_seg()
#pragma comment(linker, “/section:.SHARED,RWS”)
// end shared data

In above code, IsHomePageSet is declared as a shared variable. This variable will be use as normal variable. Value of this variable will be same in all the instance of application.

Posted in Uncategorized. Leave a Comment »

Extract embeded resource in C#

To create embedded resource, Right click on item and set BuildAction as Embeded Resource.

Now extract embedded resource use following code.

public static string ExtractEmbededResource(string resourceName)

 //look for the resource name
 resourceName = “.” + resourceName;
 foreach (string currentResource in Assembly.GetExecutingAssembly().GetManifestResourceNames())
 if (currentResource.LastIndexOf(resourceName) != -1)
 string fqnTempFile = System.IO.Path.GetTempFileName();
 string path = System.IO.Path.GetDirectoryName(fqnTempFile);
 string rootName = System.IO.Path.GetFileNameWithoutExtension(fqnTempFile);
 string destFile = path + @”\” + rootName + “.” + System.IO.Path.GetExtension(currentResource);

 System.IO.Stream fs = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(currentResource);
 byte[] buff = new byte[fs.Length];
 fs.Read(buff, 0, (int)fs.Length);

 System.IO.FileStream destStream = new System.IO.FileStream(destFile,FileMode.Create);
 destStream.Write(buff, 0, buff.Length);
 return destFile;
 return "";