Tuesday, November 19, 2013

Checking Disk Partitions and Block Size

Checking Disk Partitions and Block Size

WMI is a treasure chest full of information. This line will read local partitions along with their block sizes:

Get-WmiObject -Class Win32_Diskpartition | Select-Object -Property __Server, Caption, BlockSize 


Thanks 
Alok Kumar Sharma

Thursday, June 27, 2013

Getting error in change IPAddress,Subnet,DNSServer of the Virtual Machine using C#



private void SetNetAdapter()
        {
            string vmName = "VMURA";//D0B84C1C-E68C-4FD1-95CC-3838A30A7374

            ManagementScope _scope = new ManagementScope(@"root\virtualization\V2", null);
            ManagementObject virtualSystem = Utility.GetTargetComputer(vmName, _scope);
            ManagementObjectCollection virtualSystemSettings = virtualSystem.GetRelated//("Msvm_VirtualSystemSettingData");
            (
                "Msvm_VirtualSystemSettingData",
                "Msvm_SettingsDefineState",
                null,
                null,
                "SettingData",
                "ManagedElement",
                false,
                null
            );

         
            ManagementObject virtualSystemSetting = null;

            foreach (ManagementObject instance in virtualSystemSettings)
            {
                virtualSystemSetting = instance;
            }
            ManagementObjectCollection VMNetAdapters = virtualSystemSetting.GetRelated("Msvm_SyntheticEthernetPortSettingData");
            List<ManagementObjectCollection> NetworkSettings = new List<ManagementObjectCollection>();

            foreach (ManagementObject instanceAdp in VMNetAdapters)
            {
                NetworkSettings.Add(instanceAdp.GetRelated("Msvm_GuestNetworkAdapterConfiguration"));
            }
            var _0 = NetworkSettings[0].OfType<ManagementBaseObject>().First();
           
            _0["InstanceID"] = "2B36F20C-E133-4098-A38A-A15A35E206A8";
            _0["ProtocolIFType"] = "4096";
            _0["DHCPEnabled"] = true;
            _0["IPAddresses"] = new string[] { "192.168.63.236" };
            _0["Subnets"] = new string[] { "255.255.0.0" };
            _0["DefaultGateways"] = new string[] { "192.168.100.101" };
            _0["DNSServers"] = new string[] { "192.168.100.1" };
            virtualSystemService = Utility.GetServiceObject(scope, "Msvm_VirtualSystemManagementService");

            ManagementBaseObject inParams = virtualSystemService.GetMethodParameters("SetGuestNetworkAdapterConfiguration");
            inParams["ComputerSystem"] = virtualSystem.Path.Path;
            inParams["NetworkConfiguration"] = new ManagementBaseObject[] { _0 };

            ManagementBaseObject addAdapterOutParams = virtualSystemService.InvokeMethod("SetGuestNetworkAdapterConfiguration", inParams, null);

            using (ManagementObject job = new ManagementObject((string)addAdapterOutParams["Job"]))
            {

                job.Scope = scope;
                JobState jobState = (JobState)((ushort)job["jobState"]);

                while (!((jobState == JobState.Completed) || (jobState == JobState.CompletedWithWarnings) || (jobState == JobState.Terminated) || (jobState == JobState.Exception) || (jobState == JobState.Killed)))
                {
                    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1));
                    job.Get();
                }
                MessageBox.Show(job["ErrorDescription"].ToString());
                StringBuilder strAdptr = new StringBuilder();
                foreach (var item in job.Properties)
                {
                    strAdptr.AppendLine(item.Name + ":\t" + item.Value);
                }
                MessageBox.Show(strAdptr.ToString());
            }

}


Tuesday, June 11, 2013

A network-related or instance-specific error occurred while establishing a connection to SQL Server.
The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 1326)

A network-related or instance-specific error occurred while establishing a connection to SQL Server.
The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 1326)
Solution
Go to All Programs >> Microsoft SQL Server 2008 >> Configuration Tools >> SQL Server Configuration Manager >>SQL Server Network Configuration>>Protocols for SQLEXPRESS>>Right Click on TCP/IP >> Click on Enable
You must restart SQL Server Services for all the changes to take effect. Right click and go to menu properties to select location where default port of SQL Server can be changed.
Thanks
Alok Kumar Sharma

Thursday, January 3, 2013

Difference between Table Variable and temporary table

Feature Table Variables Temporary Tables
Scope Current batch Current session, nested stored procedures. Global: all sessions.
Usage UDFs, Stored Procedures, Triggers, Batches. Stored Procedures, Triggers, Batches.
Creation DECLARE statement only.

CREATE TABLE statement.

SELECT INTO statement.

Table name Maximum 128 characters. Maximum 116 characters.
Column data types

Can use user-defined data types.

Can use XML collections.

User-defined data types and XML collections must be in tempdb to use.
Collation String columns inherit collation from current database. String columns inherit collation from tempdb database.
Indexes Can only have indexes that are automatically created with PRIMARY KEY & UNIQUE constraints as part of the DECLARE statement. Indexes can be added after the table has been created.
Constraints PRIMARY KEY, UNIQUE, NULL, CHECK, but they must be incorporated with the creation of the table in the DECLARE statement. FOREIGN KEY not allowed. PRIMARY KEY, UNIQUE, NULL, CHECK. Can be part of the CREATE TABLE statement, or can be added after the table has been created. FOREIGN KEY not allowed.
Post-creation DDL (indexes, columns) Statements are not allowed. Statements are allowed.
Data insertion INSERT statement (SQL 2000: cannot use INSERT/EXEC).

INSERT statement, including INSERT/EXEC.

SELECT INTO statement.

Insert explicit values into identity columns (SET IDENTITY_INSERT). The SET IDENTITY_INSERT statement is not supported. The SET IDENTITY_INSERT statement is supported.
Truncate table Not allowed. Allowed.
Destruction Automatically at the end of the batch. Explicitly with DROP TABLE statement. Automatically when session ends. (Global: also when other sessions have no statements using table.)
Transactions Last only for length of update against the table variable. Uses less than temporary tables. Last for the length of the transaction. Uses more than table variables.
Stored procedure recompilations Not applicable. Creating temp table and data inserts cause procedure recompilations.
Rollbacks Not affected (Data not rolled back). Affected (Data is rolled back).
Statistics Optimizer cannot create any statistics on columns, so it treats table variable has having 1 record when creating execution plans. Optimizer can create statistics on columns. Uses actual row count for generation execution plan.
Pass to stored procedures SQL 2008 only, with predefined user-defined table type. Not allowed to pass, but they are still in scope to nested procedures.
Explicitly named objects (indexes, constraints). Not allowed. Allowed, but be aware of multi-user issues.
Dynamic SQL Must declare table variable inside the dynamic SQL. Can use temporary tables created prior to calling the dynamic sql.

Data binding in gridview using the ternary operator

Data binding in gridview using the ternary operator


<asp:GridView ID="GridView_ViewQuestionPaper" runat="server" CssClass="dataGridId"
BorderStyle="None" DataKeyNames="Qid" AutoGenerateColumns="False" ShowFooter="True"
GridLines="Vertical" CellPadding="4" BorderWidth="1px" AllowSorting="True" AllowPaging="True"
PageSize="10" OnRowCommand="GridView_ViewQuestionPaper_RowCommand" OnPageIndexChanging="GridView_ViewQuestionPaper_PageIndexChanging">
<Columns>
    <asp:TemplateField HeaderText="Delete">
        <ItemStyle Wrap="False" BorderWidth="1px" VerticalAlign="Top"></ItemStyle>
        <ItemTemplate>
            <asp:ImageButton ID="1ImgBtnDelete" runat="server"  ToolTip='<%# Eval("IsApproved").ToString().Equals("Yes".ToString()) ? Convert.ToString("Not allowed") :Convert.ToString("Delete question") %>'
            CommandName="Deleterecord" CommandArgument='<%#Eval("Qid") %>' Enabled='<%# Eval("IsApproved").ToString().Equals("Yes".ToString()) ? Convert.ToBoolean(0) : Convert.ToBoolean(1) %>' ImageUrl="../../Resources/Images/DataGrid/icon-delete.gif">
        </asp:ImageButton>
        </ItemTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>