Sunday, 10 April 2016

How to Display the IP Address of the Machine in C# Program


using System;
using System.Net;
namespace Program
{
    class MyMachine
    {
        static void Main()
        {
            String strHostName = string.Empty; //getting the Host Name.
            strHostName = Dns.GetHostName();
            Console.WriteLine("Local Machine's Host Name: " + strHostName);
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);// Using Host Name,IP address is obtained.
            IPAddress[] addr = ipEntry.AddressList;
 
            for (int i = 0; i < addr.Length; i++)
            {
                Console.WriteLine("IP Address {1} : ",addr[i].ToString());
            }
            Console.ReadLine();
        }
    }
}
------------------
OUTPUT:
Local Machine's Host Name : win7-pc
IP Address : 192.168.7.9
-----------------------------------------

Saturday, 9 April 2016

Var vs Dynamic Keywords in C#

1). var is a statically typed variable. It results in a strongly typed variable, in other words the data type of these variables are inferred at compile time. This is done based on the type of value that these variables are initialized with.

1). dynamic are dynamically typed variables. This means, their type is inferred at run-time and not the compile time in contrast to var type.

2). var type of variables are required to be initialized at the time of declaration or else they encounter the compile time error: Implicitly-typed local variables must be initialized.
2). dynamic type variables need not be initialized when declared.

3).var does not allow the type of value assigned to be changed after it is assigned to. This means that if we assign an integer value to a var then we cannot assign a string value to it. This is because, on assigning the integer value, it will be treated as an integer type thereafter. So thereafter no other type of value cannot be assigned.

3). dynamic allows the type of value to change after it is assigned to initially. if we use dynamic instead of var, it will not only compile, but will also work at run-time. This is because, at run time, the value of the variable is first inferred as Int32 and when its value is changed, it is inferred to be a string type.

4). var: Intellisense help is available for the var type of variables. This is because, its type is inferred by the compiler from the type of value it is assigned and as a result, the compiler has all the information related to the type. So we have the intellisense help available.

4). dynamic: Intellisense help is not available for dynamic type of variables since their type is unknown until run time. So intellisense help is not available. Even if you are informed by the compiler as "This operation will be resolved at run-time".

5). dynamic variables can be used to create properties and return values from a function.
5). var variables cannot be used for property or return values from a function. They can only be used as local variable in a function.

For More Details: http://goo.gl/3fSR8h

Friday, 8 April 2016

How to change password in CSharp code

using System;
using System.Data;
using System.Web.UI;

using MY.ASP.SQLServerDAL.Masters;

namespace MY.ASP.Web
{
    public partial class ChangePassword : BasePage
    {
        private const string STATUS_KEY = "Status";
        private const string TRAN_ID_KEY = "ID";

        protected void Page_Load(object sender, System.EventArgs e)
        {
            this.bcChangePassword.EditButtonVisible = false;
            this.bcChangePassword.DeleteButtonVisible = false;

            if (!IsPostBack)
            {
                ViewState[STATUS_KEY] = "Add";

                bcChangePassword.ButtonClicked = ViewState[STATUS_KEY].ToString();
            }
        }
        private void pMapControls()
        {
            LoginUserInfo.Password = WebComponents.Encryption.fnEncryptString(WebComponents.CleanString.InputText(txtConfirmPassword.Text, txtConfirmPassword.MaxLength), "352EOU1368");
            LoginUserInfo.PasswordUpdate = System.DateTime.Today.Date;

            ViewState[TRAN_ID_KEY] = LoginUserInfo;
        }
        protected void bcChangePassword_SubmitButtonClick(object sender, EventArgs e)
        {
            string lstrStatus = ViewState[STATUS_KEY].ToString();

            pMapControls();

            if (fblnValidEntry())
            {
                if (lstrStatus.Equals("Add"))
                    pUpdate();
            }
            // Response.Redirect("SignIn.aspx");
        }
        private void pUpdate()
        {
            try
            {
                LoginUserInfo = (Model.Masters.UserInfo)ViewState[TRAN_ID_KEY];

                pMapControls();

                SQLServerDAL.Masters.User.Update(Session["DB_KEY"].ToString(), LoginUserInfo);
                ProcessFlow.AccountController accountController = new ProcessFlow.AccountController();
                accountController.LogOut();
               
                //WebComponents.MessageBox.Show("Change Password - Complete.\\nYour password has been changed.\\nYour current session is closed.\\nPlease click ok to login again, using your new password", this);
                Response.Write("<script>alert('Change Password - Complete.\\nYour password has been changed.\\nYour current session is closed.\\nPlease click ok to login again, using your new password');</script>");

                //Response.Write("<script> window.parent.reload(true);</script>");
                Response.Write("<script>window.parent.location.href = 'SignIn.aspx';</script>");

                //Response.Write("<script> window.parent.location.reload(true);</script>");

                //Response.Write("<script> window.parent.close(); </script>");
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                throw;
            }
        }
        private bool fblnValidEntry()
        {
            bool lblnValue = true;

            if (Page.IsValid)
            {
                LoginUserInfo = (Model.Masters.UserInfo)ViewState[TRAN_ID_KEY];

                string lstrQuery = string.Empty;

                lstrQuery = " select gm_users_name,GM_USERS_PWD,gm_users_id"
                    + " from gm_users with (ROWLOCK)"
                    + " where GM_USERS_COMPANY_BRANCH_CODE = " + LoginUserInfo.BranchID + ""
                    + " AND GM_USERS_NAME = '" + LoginUserInfo.Name.ToString() + "'";

                DataTable myTable = SQLServerDAL.General.GetDataTable(lstrQuery);

                if (myTable.Rows.Count > 0)
                {
                    DataRow objDR = myTable.Rows[0];
                    string objUserName = objDR["gm_users_name"].ToString();
                    string objPassWord = objDR["GM_USERS_PWD"].ToString();
                    string objUserId = objDR["gm_users_id"].ToString();

                    string DecryptedPassword = Web.WebComponents.Encryption.fnDecryptString(objPassWord.ToString(), "352EOU1368");

                    if (txtOldPassword.Text != DecryptedPassword)
                    //if(WebComponents.Misc.fnEncryptString(txtExistingPwd.Text, "352EOU1368") != objPassWord.ToString())
                    {
                        bcChangePassword.Status = "Existing Password is Not Correct...!";
                        lblnValue = false;
                    }
                }
                if (txtOldPassword.Text == txtNewPassword.Text)
                {
                    bcChangePassword.Status = "Existing Password and New Password is same, please change the new Password...!";
                    lblnValue = false;
                }
                if (txtNewPassword.Text != txtConfirmPassword.Text)
                {
                    bcChangePassword.Status = "New Password and Conform PassWord Not Matching...!";
                    lblnValue = false;
                }
            }
            else
            {
                bcChangePassword.Status = "Check ur entries...!";
                lblnValue = false;
            }
            return lblnValue;
        }
        protected void bcChangePassword_CancelButtonClick(object sender, EventArgs e)
        {
            txtOldPassword.Text = "";
            txtNewPassword.Text = "";
            txtConfirmPassword.Text = "";

            bcChangePassword.Status = "";
        }
    }
}

Thursday, 7 April 2016

CSharp Program how to Check Whether the Entered Number is a Perfect Number or Not

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Program
{
    class PerfectNum
    {
        static void Main(string[] args)
        {
            int number,sum=0,x;
            Console.Write("enter the Number");
            number = int.Parse(Console.ReadLine());
            x = number;
            for (int i = 1; i < number;i++)
            {
                if (number % i == 0)
                {
                    sum=sum + i;
                }
            }
                if (sum == x)
                {
                    Console.WriteLine("\n Entered number is a perfect number");
                    Console.ReadLine();
                }
                else
                {
                    Console.WriteLine("\n Entered number is not a perfect number");
                    Console.ReadLine();
                }
            }
      }
}
-------------------------------
OUTPUT:
Enter the Number : 6
Entered Number is a Perfect Number
-----------------------------------------------

Wednesday, 6 April 2016

How to Demonstrate iDictionary Interface in CSharp Program

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, string> dict = new Dictionary<string, string>();
        dict["Tom"] = "Sunil";
        WriteKeyA(dict);
        SortedDictionary<string, string> sort = new SortedDictionary<string, string>();
        sort["Tom"] = "Malviya";
        WriteKeyA(sort);
        Console.ReadLine();
    }

    static void WriteKeyA(IDictionary<string, string> i)
    {

        Console.WriteLine(i["Tom"]);
    }
}
---------------------------------
OUTPUT:
Sunil
Malviya
------------------------------

Monday, 4 April 2016

This Man Just Raised $120 Million for a Fancy Home Juicer

At first glance, the Juicero might seem like yet another frivolous Silicon Valley undertaking.

With the admittedly eye-popping amount of capital he has raised (somewhere around $120 million, he says), though, founder Doug Evans says he has solved all of the major problems with home juicing. The Juicero is a new machine that connects to the Internet and takes nearly all of the work (and it can be a lot of work) out of making juice at home. It enables users to have a freshly made glass of juice essentially with the push of a button. The contraption costs an eye-popping $699 and users will shell out between $4 and $10 for each 8-oz. glass of juice they make.

That’s beyond pricey, especially at the high end, but the Juicero, with its novel system for ordering ingredients and turning them into juice, is “orders of magnitude” better than anything currently on the market, Evans says.

The company’s investors include a slew of big Silicon Valley names including Google Ventures and Kleiner Perkins Caufield & Byers, and food companies like Campbell Soup. One restaurant chain, Le Pain Quotidien, has already signed on to use the machines in its approximately 220 stores. “We showed it to them, and it blew their minds,” Evans says.

Commercial sales might be what the company needs achieve the kind of scale that will be required to bring prices down for home users. Juicero went to market the moment it was ready (the machines are available only in California at the moment, but the company is taking orders from all over). He’s already got several dozen engineers on staff, and he’s still hiring.


When Evans unveiled the product Thursday, the reaction in some quarters was a bit snarky. CNET called it a product “built to squeeze your wallet dry.” It’s certainly a luxury item, as were the washing machine and the automobile, both of which were dismissed by some when they were introduced. The Juicero won’t change the world like those products did, but it could conceivably go a long way toward changing the kitchen.

A cold-press machine, it looks less like a kitchen appliance than like a Macintosh computer. It’s what the machine actually does that matters most to Evans. “I wanted to scale the unscalable,” he says. Home juicing is such an arduous chore that the market has always been naturally limited to people who really love their juice (and, perhaps, to people who buy juicers that end up in their attics after a few weeks of disuse).

The Juicero is being called a “Keurig for juice,” and it really does seem to be as simple as that revolutionary single-serve coffee system.

After setting up a weekly ingredients subscription through the Juicero app, users wait for their first “packs” of chopped up mixtures of organic produce to arrive.

Users place a pack in the wi-fi-connected machine, press a button, and an 8-oz. glass of juice pours out. The packs -- which look sort of like IV bags -- bear QR codes, which are read by the machine to ensure the contents are fresh and to place an order for a replacement. So far, Juicero offers five varieties, like Spicy Greens, Sweet Roots and Carrot Beet, all containing different mixes of fruits and veggies.

The home-juicing experience itself is friction-free, but the system providing it is far from it -- hence the expense. The organic produce, shipped from one of a dozen or so participating farms mostly in California, is specially chopped by a crew in a Los Angeles warehouse and then sorted into the packs by machine. The packs are then shipped via FedEx.

Regular juicers come in several different types, the names of which promise a grisly end for bananas and celery stalks: there are, among others, masticating juicers, which chew up fruits and veggies into slush; centrifugal juicers (the most common), which slice up produce and then slam the remaining pieces against the walls of rapidly spinning drums; and cold-press juicers, which turn apples into beverages through sheer force.

The latter type offers not only a relatively merciful, quick end for your kumquats, but it also yields tastier, more nutritious juice. But like all the others, it also means a lot of work for home juices, especially at clean-up time.
Most of these juicers tend to diminish both flavor and nutrients, thanks mainly to the heat that’s generated. The biggest challenge for Evans was to devise a cold-press system that worked well in a small kitchen unit (the Juicero takes up just 9 inches of counter space). To create “8,000 lbs of force in a countertop unit,” he says, “means that you need special metals and gears that can withstand incredible forces. And we had to design custom tests and test equipment for every part.”

Evans says the machine’s “juice yield” (the amount of liquid juice that is extracted from each vegetable or piece of fruit) is between 65 percent and 70 percent at Organic Avenue, the chain he founded and sold off in 2012 (and which later went bankrupt), he says he “got about 70 percent yield from a press that cost thousands of dollars.” With Juicero, he says he’s “getting to industrial levels of efficiency … while making it available to consumers at home. Less produce for more juice is the goal.”

The Keurig coffee machine has been criticized for the environmental impact of its throwaway K-Cups. That’s an issue for the Juicero, too, but Evans says that the packs are currently recyclable, and soon will be compostable.

Although the Juicero is marketed as a home juicer, Evans says he’s also targeting the food service and office markets. He expects that this year, about 75 percent of sales will be to home users, with the rest split between restaurants and offices. When he got to Silicon Valley a few years ago, he says, he noticed “an abundance of little kitchenettes. [The companies] thought they were healthy, but they weren’t healthy.”

It was no small feat to create a home appliance that not only requires cleanup but also instantly yields what Evans says is the best-tasting, most nutritious product possible.

For the company to succeed, however, Evans will have to squeeze costs out of the system like its signature machine squeezes juice out of a lemon.

Saturday, 2 April 2016

How To append String in C sharp program

using System;
using System.Text;

public class StringProgram
{
    static void Main()
       {
        StringBuilder sb = new StringBuilder();

        sb.Append("I ").Append("Love ").Append("My... ");

        string built1 = sb.ToString();

        sb.Append("India");

        string built2 = sb.ToString();

        Console.WriteLine( built1 );
        Console.WriteLine( built2 );
    }
}
------------------------------
OUTPUT:-

I Love My...
I Love My... India
-----------------------------------------------------

Friday, 1 April 2016

How to Reading from a string one line at a time in C sharp

public class TopClass
{
    public static void Main()
    {
   
   
        string contents = "My content\r\nHi there";
        using (StringReader reader = new StringReader(contents))
        {
            int lineNo = 0;
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine("Line#{0}: {1}", ++lineNo, line);
            }
        }
    }
}
---------------
OUTPUT:-
Line#1: My content
Line#2: Hi there
-----------------------------------