Friday, July 13, 2018

Create Azure Virtual Machines using C#

Nuget:

Install-Package Microsoft.Azure.Management.Fluent

Using Statement to use :

using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;



Main Method:

 static void Main(string[] args)
        {
            //local resources
            var groupName = "dgkResourceGroup";
            var vmName = "dgkVM";
            var location = Region.USCentral;

            Console.WriteLine("Init....");
            printImageNames();
    //        var credentials = SdkContext.AzureCredentialsFactory
    //.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

//            var credentials = SdkContext.AzureCredentialsFactory
//.FromServicePrincipal("79832ed1-680b-4cbc-9b20-c63010500419", "krMN6X2PW36nkX3smxvkRVtEstvlDdV6a+WdB5mztnQ=", "77ab64d0-48c5-4723-9a64-eb43ae84e773", AzureEnvironment.AzureGlobalCloud);

//            Console.WriteLine("Authenticating...");
//            var azure = Azure
//                .Configure()
//                .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
//                .Authenticate(credentials)
//                .WithDefaultSubscription();


//                Console.WriteLine("Creating resource group...");
//            var resourceGroup = azure.ResourceGroups.Define(groupName)
//                .WithRegion(location)
//                .Create();

//            Console.WriteLine("Creating availability set...");
//            var availabilitySet = azure.AvailabilitySets.Define("dgkAVSet")
//                .WithRegion(location)
//                .WithExistingResourceGroup(groupName)
//                .WithSku(AvailabilitySetSkuTypes.Managed)
//                .Create();

//            Console.WriteLine("Creating public IP address...");
//            var publicIPAddress = azure.PublicIPAddresses.Define("dgkPublicIP")
//                .WithRegion(location)
//                .WithExistingResourceGroup(groupName)
//                .WithDynamicIP()
//                .Create();

//            Console.WriteLine("Creating virtual network...");
//            var network = azure.Networks.Define("dgkVNet")
//                .WithRegion(location)
//                .WithExistingResourceGroup(groupName)
//                .WithAddressSpace("10.0.0.0/16")
//                .WithSubnet("dgkSubnet", "10.0.0.0/24")
//                .Create();

//            Console.WriteLine("Creating network interface...");
//            var networkInterface = azure.NetworkInterfaces.Define("dgkNIC")
//                .WithRegion(location)
//                .WithExistingResourceGroup(groupName)
//                .WithExistingPrimaryNetwork(network)
//                .WithSubnet("dgkSubnet")
//                .WithPrimaryPrivateIPAddressDynamic()
//                .WithExistingPrimaryPublicIPAddress(publicIPAddress)
//                .Create();

//            Console.WriteLine("Creating virtual machine...");
//            azure.VirtualMachines.Define(vmName)
//                .WithRegion(location)
//                .WithExistingResourceGroup(groupName)
//                .WithExistingPrimaryNetworkInterface(networkInterface)
//                .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012R2Datacenter)
//                .WithAdminUsername("azureuser")
//                .WithAdminPassword("Azure12345678")
//                .WithComputerName(vmName)
//                .WithExistingAvailabilitySet(availabilitySet)
//                .WithSize(VirtualMachineSizeTypes.StandardDS1V2)
//                .Create();
            
//            #region Adding an Existing disk

//            //Console.WriteLine("Creating virtual Disk...");
//            //var managedDisk = azure.Disks.Define("dgkosdisk")
//            //            .WithRegion(location)
//            //            .WithExistingResourceGroup(groupName)
//            //            .WithWindowsFromVhd("https://mystorage.blob.core.windows.net/vhds/dgkosdisk.vhd")
//            //            .WithSizeInGB(128)
//            //            .WithSku(DiskSkuTypes.StandardLRS)
//            //            .Create();

//            //Console.WriteLine("Defining virtual machine...");
//            //azure.VirtualMachines.Define(vmName)
//            //    .WithRegion(location)
//            //    .WithExistingResourceGroup(groupName)
//            //    .WithExistingPrimaryNetworkInterface(networkInterface)
//            //    .WithSpecializedOSDisk(managedDisk, OperatingSystemTypes.Windows)
//            //    .WithExistingAvailabilitySet(availabilitySet)
//            //    .WithSize(VirtualMachineSizeTypes.StandardDS1)
//            //    .Create();

//            #endregion

//            var vm = azure.VirtualMachines.GetByResourceGroup(groupName, vmName);

//            Console.WriteLine("Details about VM");
//            Console.WriteLine("================================================================");

//            Console.WriteLine("Getting information about the virtual machine...");
//            Console.WriteLine("hardwareProfile");
//            Console.WriteLine("   vmSize: " + vm.Size);
//            Console.WriteLine("storageProfile");
//            Console.WriteLine("  imageReference");
//            Console.WriteLine("    publisher: " + vm.StorageProfile.ImageReference.Publisher);
//            Console.WriteLine("    offer: " + vm.StorageProfile.ImageReference.Offer);
//            Console.WriteLine("    sku: " + vm.StorageProfile.ImageReference.Sku);
//            Console.WriteLine("    version: " + vm.StorageProfile.ImageReference.Version);
//            Console.WriteLine("  osDisk");
//            Console.WriteLine("    osType: " + vm.StorageProfile.OsDisk.OsType);
//            Console.WriteLine("    name: " + vm.StorageProfile.OsDisk.Name);
//            Console.WriteLine("    createOption: " + vm.StorageProfile.OsDisk.CreateOption);
//            Console.WriteLine("    caching: " + vm.StorageProfile.OsDisk.Caching);
//            Console.WriteLine("osProfile");
//            Console.WriteLine("  computerName: " + vm.OSProfile.ComputerName);
//            Console.WriteLine("  adminUsername: " + vm.OSProfile.AdminUsername);
//            Console.WriteLine("  provisionVMAgent: " + vm.OSProfile.WindowsConfiguration.ProvisionVMAgent.Value);
//            Console.WriteLine("  enableAutomaticUpdates: " + vm.OSProfile.WindowsConfiguration.EnableAutomaticUpdates.Value);
//            Console.WriteLine("networkProfile");
//            foreach (string nicId in vm.NetworkInterfaceIds)
//            {
//                Console.WriteLine("  networkInterface id: " + nicId);
//            }
//            Console.WriteLine("vmAgent");
//            Console.WriteLine("  vmAgentVersion" + vm.InstanceView.VmAgent.VmAgentVersion);
//            Console.WriteLine("    statuses");
//            foreach (InstanceViewStatus stat in vm.InstanceView.VmAgent.Statuses)
//            {
//                Console.WriteLine("    code: " + stat.Code);
//                Console.WriteLine("    level: " + stat.Level);
//                Console.WriteLine("    displayStatus: " + stat.DisplayStatus);
//                Console.WriteLine("    message: " + stat.Message);
//                Console.WriteLine("    time: " + stat.Time);
//            }
//            Console.WriteLine("disks");
//            foreach (DiskInstanceView disk in vm.InstanceView.Disks)
//            {
//                Console.WriteLine("  name: " + disk.Name);
//                Console.WriteLine("  statuses");
//                foreach (InstanceViewStatus stat in disk.Statuses)
//                {
//                    Console.WriteLine("    code: " + stat.Code);
//                    Console.WriteLine("    level: " + stat.Level);
//                    Console.WriteLine("    displayStatus: " + stat.DisplayStatus);
//                    Console.WriteLine("    time: " + stat.Time);
//                }
//            }
//            Console.WriteLine("VM general status");
//            Console.WriteLine("  provisioningStatus: " + vm.ProvisioningState);
//            Console.WriteLine("  id: " + vm.Id);
//            Console.WriteLine("  name: " + vm.Name);
//            Console.WriteLine("  type: " + vm.Type);
//            Console.WriteLine("  location: " + vm.Region);
//            Console.WriteLine("VM instance status");
//            foreach (InstanceViewStatus stat in vm.InstanceView.Statuses)
//            {
//                Console.WriteLine("  code: " + stat.Code);
//                Console.WriteLine("  level: " + stat.Level);
//                Console.WriteLine("  displayStatus: " + stat.DisplayStatus);
//            }
//            Console.WriteLine("Press enter to continue...");
//            Console.ReadLine();



        }





public static void printImageNames()
        {
            var credentials = SdkContext.AzureCredentialsFactory
.FromServicePrincipal("79832ed1-680b-4cbc-9b20-c63010500419", "krMN6X2PW36nkX3smxvkRVtEstvlDdV6a+WdB5mztnQ=", "77ab64d0-48c5-4723-9a64-eb43ae84e773", AzureEnvironment.AzureGlobalCloud);

            Console.WriteLine("Authenticating...");
            var azure = Azure
                .Configure()
                .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                .Authenticate(credentials)
                .WithDefaultSubscription();

            var publishers = azure
                   .VirtualMachines
                   .Sizes
                   .ListByRegion(Region.USCentral);

            foreach (var publisher in publishers)
            {
                Console.WriteLine(publisher.Name);
                //if(StringComparer.OrdinalIgnoreCase.Equals(publisher.Name, "MicrosoftWindowsDesktop") || StringComparer.OrdinalIgnoreCase.Equals(publisher.Name, "MicrosoftWindowsServer"))
                //{
                //    foreach (var offer in publisher.Offers.List())
                //    {
                //        foreach (var sku in offer.Skus.List())
                //        {
                //            foreach (var image in sku.Images.List())
                //            {
                //                Console.WriteLine($"Image - {publisher.Name}/{sku.Name}/{image.Version}");

                //            }
                //        }
                //    }
                //}
                
            }
            Console.Read();

        }

Monday, December 19, 2016

Query Active Directory Directly From SharePoint

public static string getBrManagerFromAD(string ou)
        {
            using (HostingEnvironment.Impersonate())
            {
                string ouReplace = "";
                if (ou.Contains("-"))
                {
                    ouReplace = ou.Split('-')[0].Split(' ')[0];
                }
                string managerName = "";
                try
                {
                    List<Principal> allUsers = new List<Principal>();

                    // create your domain context and define the OU container to search in
                    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "ABC.LOCAL",
                                                                "OU=Users," + "OU=" + ouReplace + ",OU=Branch Offices,DC=ABC,DC=Local");

                    // define a "query-by-example" principal - here, we search for a UserPrincipal (user)
                    UserPrincipal qbeUser = new UserPrincipal(ctx);

                    // create your principal searcher passing in the QBE principal  
                    PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

                    // find all matches
                    foreach (var found in srch.FindAll())
                    {
                        // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....        
                        allUsers.Add(found);

                    }
                    foreach (Principal user in allUsers)
                    {
                        if (!string.IsNullOrEmpty(user.DistinguishedName))
                        {
                            DirectoryEntry dex = new DirectoryEntry("LDAP://" + user.DistinguishedName);

                            if (dex != null)
                            {
                                if (dex.Properties["title"].Count > 0)
                                {
                                    if ((string)dex.Properties["title"].Value == "Manager")
                                    {
                                        managerName = (string)dex.Properties["displayName"].Value;
                                    }
                                }
                            }
                        }
                    }


                }
                catch (Exception e)
                {
                    Logging.SaveErrorLogData(e.Message, "getBrManagerFromAD");
                }

                return managerName;
            }
        }

Sunday, December 18, 2016

How to Hide Sharepoint Cog (Gear)

1. On SharePoint Designer Choose the relevant Master Page
2. Then Search for  "<SharePoint:SiteActions"
3. Paste Visible="false" after LargeIconMode="false"


Monday, February 15, 2016

Give Proper permission through Run SPSecurity.RunWithElevatedPrivileges

 SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPSite site = SPContext.Current.Site;

                SPWeb web = SPContext.Current.Web;

                using (SPSite newSite = new SPSite(site.ID))
                {
                    using (SPWeb newWeb = newSite.OpenWeb(web.ID))
                    {
                        foreach (SPGroup group in newWeb.Groups)
                        {
                            foreach (SPUser u in group.Users)
                            {
                                if (SPContext.Current.Web.CurrentUser.Name == u.Name)
                                {
         SPQuery depquery = new SPQuery();
         depquery.Query = "<Where><Contains><FieldRef Name='Title' /><Value Type='Text'>" + group.Name + "</Value></Contains></Where>";
         SPListItemCollection item = SPContext.Current.Web.Lists[Constants.HNBDepartmentList()].GetItems(depquery);

                                    if (item.Count > 0)
                                    {
                                        grpName = group.Name;
                                    }
                                }
                            }
                        }
                    }
                }



            });

Sunday, February 7, 2016

Monday, February 1, 2016

Adding and Install .wsp to a Site Collection using Powershell Commands

Stsadm

To Add : stsadm –o addsolution –name SharePointProject2.wsp

To Install : stsadm –o deploysolution –name SharePointProject2.wsp –url http://moss-server –allowCasPolicies –immediate

To Upgrade : stsadm –o upgradesolution –name SharePointProject2.wsp –filename SharePointProject2.wsp –immediate –allowCasPolicies


PowerShell

To Add : Add-SPSolution c:\code\SharePointProject2\bin\debug\SharePointProject2.wsp

To Install : Install-SPSolution –Identity SharePointProject2.wsp –WebApplication http://sp2010 -GACDeployment

To Update : Update-SPSolution –Identity SharePointProject2.wsp –LiteralPath c:\code\SharePointProject2\bin\debug\SharePointProject2.wsp –GACDeployment

To Uninstall : Uninstall-SPSolution –Identity SharePointProject2.wsp –WebApplication http://sp2010

To Remove : Remove-SPSolution –Identity SharePointProject2.wsp

Wednesday, January 27, 2016

Service Account Setup for Sharepoint 2013

Account name
Role
Domain rights
Local SharePoint Server rights needed
SQL rights needed
sp_install
Used to install SharePoint binaries.
Domain User
Local administrator on all SharePoint boxes
public, dbcreator, and securityadmin SQL roles. Need to be SysAdmin on SQL when installing the Workflow Manager
sp_farm
Farm account. Used for Windows Timer Service, Central Admin and User Profile service
Domain User
Local Admin during UPS provisioning, log on locally right
None
sp_webapp
App pool id for content web apps
Domain User
None
None
sp_serviceapps
Service app pool id
Domain User
None
None
sp_content 
Default account used by Search Service Application to crawl content
Domain User
None
None
sp_userprofile1
Account used by the User Profile services to access Active Directory
Must have Replicating Change permissions to AD. Must be given in BOTH ADUC and ADSIEDIT. If domain is Windows 2003 or early, must also be a member of the "Pre-Windows 2000" built-in group.
None
None
sp_superuser2
Cache account
Domain User
Web application Policy Full Control
Web application super account setting
None
sp_superreader2
Cache account
Domain User
Web application Policy Full read
Web application super reader account setting
None
​sqlinstall​Account SQL is installed with​Domain UserNone​Local Administrator on the SQL box
​sqluserAccount the SQL Instance is running as.Domain UserNoneWill be given necessary permissions when SQL Server is installed by a local administrator on the SQL box