Sunday 30 November 2014

C# Active Directory fuctions

//Check user exist in a group
public static bool IfUserExistInGroup(string username, string groupname)
       {
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DOMAINNAME");
 
           // find a user
           UserPrincipal user = UserPrincipal.FindByIdentity(ctx, username);
 
           // find the group in question
           GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupname);
 
           // check if user is member of that group
           if (user.IsMemberOf(group))
           {
               return true;
           }
           else
               return false;
 
       }
//Check if group exist
public static bool ifGroupExist(string groupname)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
                                           "domain",
                                           "admin",
                                           "Password");
 
            GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx,
                                                       IdentityType.SamAccountName,
                                                       groupname);
 
 
            if (grp != null)
            {
                grp.Dispose();
                ctx.Dispose();
                return true;
 
            }
            else
            {
                ctx.Dispose();
                return false;
            }
 
 
        }
//if user exist
 public static bool ifUserExist(string username)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
                                           "domain",
                                           "admin",
                                           "password");
 
            UserPrincipal usr = UserPrincipal.FindByIdentity(ctx,
                                                       IdentityType.SamAccountName,
                                                       username);
 
 
            if (usr != null)
            {
                usr.Dispose();
                ctx.Dispose();
                return true;
 
            }
            else
            {
                ctx.Dispose();
                return false;
            }
 
 
        }

//Find if user is administrator
 
public static bool IsAdministrator()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
 
            if (null != identity)
            {
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                return principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
 
            return false;
        }
//set home directory 
public static string setHomeDir(string username, string homeDir)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
                                         "",
                                         "",
                                         "");
 
            UserPrincipal usr = UserPrincipal.FindByIdentity(ctx,
                                                       IdentityType.SamAccountName,
                                                       username);
 
            if (usr != null)
            {
                if (usr.Enabled == false)
                    usr.Enabled = true;
                usr.HomeDirectory = homeDir;
                try
                {
                    usr.Save();
                }
                catch (Exception e)
                {
                    return e.ToString();
                }
                usr.Dispose();
 
            }
            else { return "cant find user"; }
            ctx.Dispose();
            return ("succssful");
 
 
        }
//Create user
public static void createUser(string username, string password, string firstname, string surname, string yearlevel, string homegroup)
        {
            if (ifUserExist(username))
                writeToLogs("user:" + username + " already exist", ADUserlogs);
            else
            {
                PrincipalContext pc = new PrincipalContext(ContextType.Domain,
                                                       "DomainName",
                                                       "AdminName",
                                                       "");
                UserPrincipal up = new UserPrincipal(pc);
                up.SamAccountName = username;
                up.HomeDirectory = "\\\\FileServer$\\" + username;
                if (!Directory.Exists(up.HomeDirectory))
                {
                    Directory.CreateDirectory(up.HomeDirectory);
                    AddDirectorySecurity(up.HomeDirectory, username, FileSystemRights.FullControl);
                }
 
                up.EmailAddress = username + "@Email.com";
 
                up.SetPassword(password);
                up.Enabled = true;
                up.ExpirePasswordNow();
                up.GivenName = firstname;
                up.Surname = surname;
                up.DisplayName = firstname + " " + firstname;
                up.HomeDrive = "U:";
                up.Description = "Year " + yearlevel + " 2014";
 
                try
                {
                    up.Save();
                    up.Dispose();
                    pc.Dispose();
                }
                catch (Exception E)
                {
                    Console.WriteLine(E.ToString());
                    up.Dispose();
                    pc.Dispose();
 
                }
                writeToLogs("user:" + username + "at yearlevel:" + yearlevel + "successfully created with password:" + password, ADUserlogs);
                string studentOU;
                if (homegroup != "condition1")
                    studentOU = "OU1"
                else
                    studentOU = "";
                moveOU(getDN(username), studentOU);
 
         }
        }

// create ou
public static void createou(string ou, string rootou)
        {
            string rootOU = rootou;
            DirectoryEntry objAD = new DirectoryEntry(rootOU, "i", "");
            DirectoryEntry objOU = objAD.Children.Add(ou, "OrganizationalUnit");
            objOU.CommitChanges();
        }

//Change group scope
public static void changeGroupScope(string s, GroupScope gp)
        {
            try
            {
                PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
                // find the group in question
                GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, s);
                group.GroupScope = gp;
                group.Save();
            }
            catch (Exception E)
            {
                writeToLogs(E.ToString() + " --- when try to make changes on group name: " + s, ADGrouplogs);
            }
 
 
        }

//Remove Directory Security
 public static void RemoveDirectorySecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
        {
            // Create a new DirectoryInfo object.
            DirectoryInfo dInfo = new DirectoryInfo(FileName);
 
            // Get a DirectorySecurity object that represents the  
            // current security settings.
            DirectorySecurity dSecurity = dInfo.GetAccessControl();
 
            // Add the FileSystemAccessRule to the security settings. 
            dSecurity.RemoveAccessRule(new FileSystemAccessRule(Account,
                                                            Rights,
                                                            ControlType));
 
            // Set the new access settings.
            dInfo.SetAccessControl(dSecurity);
 
        }

//Add  AD security
public static bool AddDirectorySecurity(string FileName, string Account, FileSystemRights Rights)
        {
            try
            {
                // Create a new DirectoryInfo object.
                DirectoryInfo dInfo = new DirectoryInfo(FileName);
 
                // Get a DirectorySecurity object that represents the  
                // current security settings.
                DirectorySecurity dSecurity = dInfo.GetAccessControl();
 
                // Add the FileSystemAccessRule to the security settings. 
                dSecurity.ResetAccessRule(new FileSystemAccessRule(Account,
           Rights, AccessControlType.Allow));
                dSecurity.AddAccessRule(new FileSystemAccessRule(Account,
            Rights,
            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
            PropagationFlags.InheritOnly,
            AccessControlType.Allow));
 
                /*
                dSecurity.AddAccessRule(new FileSystemAccessRule(Account,
                                                                Rights,
                                                                ControlType));
                */
 
 
                // Set the new access settings.
                dInfo.SetAccessControl(dSecurity);
                return true;
            }
            catch (Exception E)
            {
                return false;
            }
 
 
        }

// move OU
 public static string moveOU(string userDN, string ou)
        {
            try
            {
                DirectoryEntry NewUser = new DirectoryEntry("LDAP://" + userDN);
                // Use the MoveTo property to define the new container you want to move the object to.
                NewUser.MoveTo(new DirectoryEntry("LDAP://" + ou));
            }
            catch (Exception e)
            {
                writeToLogs("when move :" + userDN + " to " + ou + " , this happened" + e.ToString(), ADOUlogs);
            }
            return ("success");
        }

//get Distinguish Name
public static string getDN(string username)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
                                           "",
                                           "",
                                           "Password");
 
            UserPrincipal usr = UserPrincipal.FindByIdentity(ctx,
                                                       IdentityType.SamAccountName,
                                                       username);
 
 
            if (usr != null)
            {
                string temp = usr.DistinguishedName.ToString();
                usr.Dispose();
                ctx.Dispose();
                return temp;
 
            }
            else
            {
 
                ctx.Dispose();
                return "cant find user";
            }
 
 
 
        }
//add user to a group
public static string AddUserToGroup(string userId, string groupName)
        {
            if (ifUserExist(userId))
            {
                if (!IfUserExistInGroup(userId, groupName))
                {
                    try
                    {
 
                        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
                        // find the group in question
                        GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName);
                        UserPrincipal user = UserPrincipal.FindByIdentity(ctx, userId);
                        group.Members.Add(user);
                        group.Save();
                        group.Dispose();
                        user.Dispose();
                        ctx.Dispose();
 
                    }
                    catch (System.DirectoryServices.AccountManagement.PrincipalExistsException)
                    {
                        return userId + " is already a member of " + groupName;
                    }
                    catch (System.DirectoryServices.DirectoryServicesCOMException E)
                    {
                        return E.Message.ToString() + "WHen try to add: " + userId + " to group:" + groupName;
 
                    }
                    return userId + " is successfully added to " + groupName;
                }
                else
                    return userId + " is already a member of " + groupName;
            }
            else
                return userId + " is not exist";
 
        }
//empty active directory group 
 public static string emptyGroup(string groupname)
        {
            string output = "Empty Group started";
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
            // find the group in question
            GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupname);
            // if found....
            if (group != null)
            {
                // iterate over members
                foreach (Principal p in group.GetMembers())
                {
 
                    UserPrincipal theUser = p as UserPrincipal;
                    if (theUser != null)
                    {
                        group.Members.Remove(theUser);
                        try
                        {
                            group.Save();
 
                        }
                        catch (Exception e)
                        {
                            output = e.ToString();
                        }
                        finally { }
                    }
 
                }
            }
            return output;
        }
//create active directory group
public static string createGroup(string Path, string name)
        {
            if (!DirectoryEntry.Exists(Path))
            {
                try
                {
                    DirectoryEntry entry = new DirectoryEntry(Path);
                    DirectoryEntry group = entry.Children.Add("CN=" + name, "group");
                    group.Properties["sAmAccountName"].Value = name;
                    group.CommitChanges();
                    return "group: " + name + " has been created ";
                }
                catch (Exception e)
                {
                    return e.Message.ToString();
                }
            }
            else
            {
                return emptyGroup(name);
            }
        }
 

C# File System

//Count lines in file
 public static int CountLinesInFile(string f)
        {
            int count = 0;
            using (StreamReader r = new StreamReader(f))
            {
                string line;
                while ((line = r.ReadLine()) != null)
                {
                    count++;
                }
            }
            return count;
        }

//Create Folder
  public static string createDir(string s)
        {
            try
            {
                // Determine whether the directory exists. 
                if (Directory.Exists(s))
                {
                    return ("That path:" + s + " exists already.");
 
                }
 
                // Try to create the directory.
                DirectoryInfo di = Directory.CreateDirectory(s);
                return ("The directory :" + s + "was created successfully at " + Directory.GetCreationTime(s));
 
 
            }
            catch (Exception e)
            {
                return ("The process failed: " + e.ToString() + " when create:" + s);
            }
            finally { }
        }

C# run DOS command

public static void LaunchCommandLineApp(string command, string args)
        {
 
            // Use ProcessStartInfo class
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.CreateNoWindow = false;
            startInfo.UseShellExecute = false;
            startInfo.FileName = command;
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            startInfo.Arguments = args;
 
            try
            {
                // Start the process with the info we specified.
                // Call WaitForExit and then the using statement will close.
                using (Process exeProcess = Process.Start(startInfo))
                {
                    exeProcess.WaitForExit();
                }
            }
            catch
            {
                // Log error.
            }
        }

get date time in YYYYYMMDDHHMMSS format

public static string getDateTime()
        {
            return (DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString());
        }     

C# Fix Internet Explorer with wpad proxy

 public static void IEFix()
        {
            foreach (Process proc in Process.GetProcessesByName("iexplore.exe"))
            {
                proc.Kill();
            }
 
            RegistryKey startPageKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\Main", true);
            startPageKey.SetValue("Start Page", "http://");
            startPageKey.Close();
 
            RegistryKey startPageKey2 = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            startPageKey2.SetValue("AutoConfigURL", "http:///wpad.dat");
            startPageKey2.Close();
            Tools.LaunchCommandLineApp("C:\\Program Files\\Internet Explorer\\iexplore.exe", "");
        }

C# Get Serial Number

import System.Management;
public static string getSN()
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_Processor");
            string collectedInfo = ""; // here we will put the informa
 
            searcher.Query = new ObjectQuery("select * from Win32_BIOS");
            foreach (ManagementObject share in searcher.Get())
            {
                //then, the serial number of BIOS
                collectedInfo += share.GetPropertyValue("SerialNumber").ToString();
            }
            return collectedInfo;
        }

C# SQL Server Examples

This is for a quick reference whenever I need use some data from SQL server:
1. From SQL to DataTable:
SqlConnection myConnection = new SqlConnection("user id=;" +
                                      "password=;server=;" +
                                      "database=; " +
                                      "connection timeout=30");
        myConnection.Open();
        SqlCommand command = new SqlCommand("Select xxx from xxx here xxx =xxx order by xxx", myConnection);
        // Creates a SqlDataReader instance to read data from the table.
        SqlDataReader dataReader = command.ExecuteReader();

DataTable dt = new DataTable();
dt.Load(dataReader);


2. From DataTable to String Builder
var sb = new StringBuilder();
string[] columnNames = dt.Columns.Cast().
                                  Select(column => column.ColumnName).
                                  ToArray();
        sb.AppendLine(string.Join(",", columnNames));
 
        foreach (DataRow row in dt.Rows)
        {
            string[] fields = row.ItemArray.Select(field => field.ToString()).
                                            ToArray();
            sb.AppendLine(string.Join(",", fields));
        }
3. From DataTable to GridView
this.GridView1.Visible = true;
GridView1.DataSource = dt;
GridView1.DataBind();
4.From DataTable to CSV
StringBuilder sb = new StringBuilder();  
string[] columnNames = dt.Columns.Cast().
                                  Select(column => column.ColumnName).
                                  ToArray();
sb.AppendLine(string.Join(",", columnNames));
 
foreach (DataRow row in dt.Rows)
{
    string[] fields = row.ItemArray.Select(field => field.ToString()).
                                    ToArray();
    sb.AppendLine(string.Join(",", fields));
} 
File.WriteAllText("test.csv", sb.ToString())

Reference: http://stackoverflow.com/questions/4959722/c-sharp-datatable-to-csv

C# Change File Extension



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace RenameExt
{
    public partial class Form1 : Form
    {
        string[] files;
         
       
        public Form1()
        {
            InitializeComponent();
        }
 
         
 
        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult result = folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                //
                // The user selected a folder and pressed the OK button.
                // We print the number of files found.
                //
              files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
     
              foreach (string file in files)
              {
 
                  richTextBox1.AppendText(file.ToString() + Environment.NewLine);
                   
              }
 
            }
 
 
 
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            foreach (string file in files)
            {
                File.Move(file, Path.ChangeExtension(file, textBox1.Text));
 
            }
            files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
 
            richTextBox1.AppendText("You have changed following files "+Environment.NewLine);
            foreach (string file in files)
            {
 
                richTextBox1.AppendText(file.ToString() + Environment.NewLine);
 
            }
 
        }
 
        private void button3_Click(object sender, EventArgs e)
        {
            foreach (string file in files)
            {
               File.Move(file,file.Substring(0,file.Length-4));
              
 
            }
 
            files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
 
            richTextBox1.AppendText("You have changed following files " + Environment.NewLine);
            foreach (string file in files)
            {
 
                richTextBox1.AppendText(file.ToString() + Environment.NewLine);
 
            }
        }
 
        
    }
}

C# Image Merger



This is a Banner creator for one of our users since she doesnt know how to combine pictures.
The idea is make a Banner with 4 pictures, so she can easily add pictures and click export button to save it into one.
It was referenced from http://stackoverflow.com/questions/14661919/merge-png-images-into-single-image-in-wpf
Also as you can see, if we play with the template a bit and choose different combination of picture orders and also make a single radio seletion list, the combine method can be overload as many way as you want. (Vertical, Rectangle, etc) You only need specify how the image frames are drawn. Also if you enable drop on the controls, you can also get drop file directly however you may need go through all the control by name and assgn the files to them. There would be a lot potential on this. However the core functions are below.
Code:
MainWindow.xaml

    
        
        
        
        
        

MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.Drawing;
using System.IO;
 
 
namespace Draw
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
         
        public MainWindow()
        {
            InitializeComponent();
           
 
            
        }
 
        public void Button_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            op.Title = "Select a picture";
            op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
                "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
                "Portable Network Graphic (*.png)|*.png";
            if (op.ShowDialog() == true)
            {
                image1.Source = new BitmapImage(new Uri(op.FileName));
            }
            lb1.Content = op.FileName;
             
            
            
 
        }
 
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            OpenFileDialog op2 = new OpenFileDialog();
            op2.Title = "Select a picture";
            op2.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
                "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
                "Portable Network Graphic (*.png)|*.png";
            if (op2.ShowDialog() == true)
            {
                image2.Source = new BitmapImage(new Uri(op2.FileName));
            }
            lb2.Content = op2.FileName;
 
        }
 
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            OpenFileDialog op3 = new OpenFileDialog();
            op3.Title = "Select a picture";
            op3.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
                "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
                "Portable Network Graphic (*.png)|*.png";
            if (op3.ShowDialog() == true)
            {
                image3.Source = new BitmapImage(new Uri(op3.FileName));
            }
            lb3.Content = op3.FileName;
 
        }
 
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            OpenFileDialog op4 = new OpenFileDialog();
            op4.Title = "Select a picture";
            op4.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
                "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
                "Portable Network Graphic (*.png)|*.png";
            if (op4.ShowDialog() == true)
            {
                image4.Source = new BitmapImage(new Uri(op4.FileName));
            }
            lb4.Content = op4.FileName;
 
        }
        public void COmbine(string filepath) {
            // Loads the images to tile (no need to specify PngBitmapDecoder, the correct decoder is automatically selected)
            BitmapFrame frame1 = BitmapDecoder.Create(new Uri(lb1.Content.ToString()), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();
            BitmapFrame frame2 = BitmapDecoder.Create(new Uri(lb2.Content.ToString()), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();
            BitmapFrame frame3 = BitmapDecoder.Create(new Uri(lb3.Content.ToString()), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();
            BitmapFrame frame4 = BitmapDecoder.Create(new Uri(lb4.Content.ToString()), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();
 
            // Gets the size of the images (I assume each image has the same size)
           
 
            // Draws the images into a DrawingVisual component
            DrawingVisual drawingVisual = new DrawingVisual();
            using (DrawingContext drawingContext = drawingVisual.RenderOpen())
            {
                drawingContext.DrawImage(frame1, new Rect(0, 0, 237, 150));
                drawingContext.DrawImage(frame2, new Rect(238, 0, 237, 150));
                drawingContext.DrawImage(frame3, new Rect(476,0 , 237, 150));
                drawingContext.DrawImage(frame4, new Rect(714, 0, 237, 150));
            }
 
            // Converts the Visual (DrawingVisual) into a BitmapSource
            RenderTargetBitmap bmp = new RenderTargetBitmap(950, 150, 96, 96, PixelFormats.Pbgra32);
            bmp.Render(drawingVisual);
 
            // Creates a PngBitmapEncoder and adds the BitmapSource to the frames of the encoder
            PngBitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bmp));
 
            // Saves the image into a file using the encoder
            using (Stream stream = File.Create(filepath))
                encoder.Save(stream);
        }
 
        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            SaveFileDialog fp = new SaveFileDialog();
            fp.Filter = "JPG|*.JPG";
            if (fp.ShowDialog() == true)
            { 
            COmbine(fp.FileName);
            }
        }
         
 
    }
}

C# Read CSV

var lineCount = System.IO.File.ReadLines(@"123.csv").Count();
var reader = new StreamReader(System.IO.File.OpenRead(@"123.csv"));
            for (int i = 0; i < lineCount; i++)
            {
                var line = reader.ReadLine();
                var values = line.Split(',');
                string value1 = values[0];
                string value2 = values[1];
  /* deal with it */
 
            }

C# background worker example

1. XAML:

    
        



2. CS:\
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
using System.ComponentModel;
using System.Security.AccessControl;
 
 
namespace PC_HELP
{
    /// 
    /// Interaction logic for FixFolders.xaml
    /// 
    public partial class FixFolders : Window
    {
        BackgroundWorker m_oWorker;
 
        
 
        public FixFolders()
        {
            InitializeComponent();
            m_oWorker = new BackgroundWorker();
 
            // Create a background worker thread that ReportsProgress &
            // SupportsCancellation
            // Hook up the appropriate events.
            m_oWorker.DoWork += new DoWorkEventHandler(m_oWorker_DoWork);
            m_oWorker.ProgressChanged += new ProgressChangedEventHandler
                    (m_oWorker_ProgressChanged);
            m_oWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler
                    (m_oWorker_RunWorkerCompleted);
            m_oWorker.WorkerReportsProgress = true;
            m_oWorker.WorkerSupportsCancellation = true;
        }
 
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            m_oWorker.RunWorkerAsync();
        }
        void m_oWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        { }
        void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
 
            // This function fires on the UI thread so it's safe to edit
 
            // the UI control directly, no funny business with Control.Invoke :)
 
            // Update the progressBar with the integer supplied to us from the
 
            // ReportProgress() function.  
 
            PG1.Value = e.ProgressPercentage;
            lblStatus.Text = "Processing......" + PG1.Value.ToString() + "%";
        }
        void m_oWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            // The sender is the BackgroundWorker object we need it to
            // report progress and check for cancellation.
            //NOTE : Never play with the UI thread here...
 
            string[] folders = System.IO.Directory.GetDirectories(@"", "*", System.IO.SearchOption.TopDirectoryOnly);
 
            StringBuilder sb = new StringBuilder();
            MessageBox.Show(folders[5].Substring(18));
            for (int i = 0; i <= folders.Length - 1; i++)
            {
                BSCLib.AddDirectorySecurity(folders[i], folders[i].Substring(18), FileSystemRights.FullControl);
                m_oWorker.ReportProgress(i*100/folders.Length);
                    if (m_oWorker.CancellationPending)
                {
                    // Set the e.Cancel flag so that the WorkerCompleted event
                    // knows that the process was cancelled.
                    e.Cancel = true;
                    m_oWorker.ReportProgress(0);
                    return;
                }
            }
 
            //Report 100% completion on operation completed
            m_oWorker.ReportProgress(100);
        }
 
 
 
    }
}

Reference:

http://www.codeproject.com/Articles/99143/BackgroundWorker-Class-Sample-for-Beginners

Sharepoint - Simple Slides Show

Preparation: Download jquery-1.4.4.min.js from jquery website. Download jquery.cycle.all.js from jquery cycle website. Copy them to Sharepoint site, in my case, I set up a folder called img under root. Then paste 6 images and two scripts to it. The images name are 1.jpg-6.jpg.
You need add 2 js to the      master page. Go to the master page of the current one through sharepoint      designer 2010. Edit it. Find <head runat="server">      area, add twos lines after it:




2.Now you need save the master page, then      publish and approve it at the website. You need login to your sharepoint      website ,site actions-> site settings->Galleries->master page and      page layouts->find the master page you edited and publish it, then      check on it and then approve it from the icon at the top.

3.The Jscripts are ready to      run, from the page which using the same master page, create a content      editor webpart, select web part, click on edit html source, paste the      following code to it:




                         
    
Beach 1 Beach 2 Beach 2 Beach 4 Beach 5 Beach 5

Sharepoint - Prepare your site public faced website

Our public site just went online yestarday, phew.

After a while being busy, and drived crazy by Sharepoint, I finally built my confidence to customize Sharepoint, Now it is time to organize those knowledge.

I got help from many blogs, and I really appreciate those authors who wrote those brilliant articles, without those, I dont think I can get our site online.

1. Prepare your public faced website.

I have been get issues with publish my team work site to public, and after some research, I feel it is a very good way is to do it from scratch(I destroyed and rebuilt my site four times to made it clear) . Here are the steps.

1. After installation of Sharepoint, it will create a default site and took 80 port, so we need delete it, if you did not install the default one, skip this step.
2. Create your base web application, i would give port 8080 for the local one, make it open anonymous to public. Create a site collection on that application, I would use publish portal instead of team site.

3. Extend the base web application with its public http header and port 80, go to IIS and change the authentication to anonymous and form only.

4. Make sure all the template and all the documents are published. If you get 401 authorization error, congratulations, your IIS is setup correctly, you only need check all the related template, master page, even the images are published.
5. Remeber go to library of images and change its setting, turn off versionning.

When all of these have been done, we can start customization.

Sharepoint 2010 Search Page For Anonymous

I have been to many website and gathered a lot information to get this done, bascically when u make a website avalabe, the search function is not working or not working for anonymous user or not working at all. If it is not working at all, please check my another post. –http://rockyoz.wordpress.com/2012/01/27/sharepoint-public-website-customization-bloody-hell/

FYI, it is not hell any more :) It is like heaven right now lol.

My situation is when search function is worked for users, it is not work for anonymous.

So to fix it.

1. go to site settings->site aministration-> search and offline avalability-> Always index all Web Parts on this site tick

2. go to site settings->Site Collection administration->Site Collection FEature->Search Server Web Parts ->active

3. create another publish page, maybe just use main body, insert webpart->Search->Search Core Results

4.Search Core Results ->Location properties->Local Search Results

5.Score -> All sites( you can go to Site Settings->Site Collection Administration->Search Scopes) . Save it  and Publish the Page.

6. Site Settings->Search Settings->Site Collection Search Results Page-> type in the search page u just created, done!

sharepoint public website customization

Ok. So many days struggling. The problem been fixed one by another. here are the problems.

1. anonymous access without login prompt.

create a main site on 8080 port. give it a intranet host header.

Enable anonymous access both on central administration and website.

extend it on 80 port, give it a internet host header.

On IIS only enable the anonymous authentication for 80 port new site.

MAKE SURE EVERYTHING IS CHECKED IN AND PUBLISHED!!!!

2. Picture can not be seen by anonymous user.

TURN OFF PICTURE LIBRARY VERSIONING.

MAKE SURE PICTURE IS CHECKED IN! BLoody Hell.

3. anonymous user seen different background or master page or css than normal user!

MAKE SURE MASTER TEMPLATE AND CSS ARE PUBLISHED OR CHECKED IN.

4. Anonymous user can not see the content of content query web part.

I followed both, but i am not sure which one solved my problem , because it was cured instantly but after I have checked in manythings that i could not remember, as long as it is working now. I dont want touch it!!!

http://blog.mastykarz.nl/inconvenient-sharepoint-2010-content-query-web-part-anonymous-access/

http://sharepointyankee.com/2010/12/10/content-query-web-parts-anonymous-access-and-the-dreaded-copyutil-aspx-in-sharepoint-2010/

I really want to believe the second thread is more like the queue, although i am not sure. But at least it is not a problem at the moment.

5. hide login for anonymous users

<Sharepoint:SPSecurityTrimmedControl>

6. hide ribbon, same.

To make a login for users. I just use another master page to do it.

I have 3 master page. Home for welcome page, main for websites,  and login.master for users to login.

7.

Error an unhandled exception occurred in the Silverlight Application when creating SharePoint 2010 Sites
http://ianankers.wordpress.com/2011/09/12/error-an-unhandled-exception-occurred-in-the-silverlight-application-when-creating-sharepoint-2010-sites/

8. Database need upgrade

http://blogs.technet.com/b/sbs/archive/2011/05/24/you-must-manually-run-psconfig-after-installing-sharepoint-2010-patches.aspx

9. Anonymous user can not use search, check my another post->

http://rockyoz.wordpress.com/2012/01/30/enable-search-for-anonymous-user-in-sharepoint-2010/

10.

OOTB Navigation fix to support IPad & I-Devices
http://tommdaly.wordpress.com/2011/11/10/ootb-navigation-fix-to-support-ipad-i-devices/

11.

Fast rounded corners in Photoshop
http://matthom.com/archive/2004/09/10/fast-rounded-corners-in-photoshop

12. Googlemap

http://support.google.com/maps/bin/answer.py?hl=en&answer=72644

13. Insert content editor webpart into page, put html code like this.

http://FILENAME.PDF
14. website is not working on iphone

http://blogs.pointbridge.com/Blogs/nielsen_travis/Pages/Post.aspx?_ID=46

15. Website is not working on win7 phone or Android phone
go to \app_broweser\compat.brower
Change isMobileDevice under android and win7 to false. save it.

Sharepoint 2010 Anonymous Access

after 2 days of failures and 401 or blank pages, i still got login prompt and never get anonymous access.

Finally.

I got it.

First of all. dont change any settings on intranet,

THen make a extension on the existing one, the http header is the internet webaddress

now go to iis, give the newly showed up session anonymous access and form access.

Go to the mainly web application, give anonymous access. DONE!

Detailed reference:http://www.c-sharpcorner.com/uploadfile/bhushangawale/creating-anonymous-site-using-sharepoint-existing-web-application/

Sharepoint No Sandboxed Server

Error: No available sandboxed code execution server could be found.
SP 2010 Central Admin > App Management > Service Apps > Manage Services on Server-> Restart SharePoint Foundation Sandbox Code Service

Sharepoin Layout and hide ribbon

1)      Open your SharePoint master page

2)      Locate this line: <div id=”s4-ribbonrow”>

3)      Change it to: <div id=”s4-ribbonrow” style=”display:none”>

4)      Now find the end of the “s4-ribbonrow” tag and add following block right after it: <Sharepoint:SPSecurityTrimmedControl ID=”SPSecurityTrimmedControl2″ runat=”server” PermissionsString=”AddAndCustomizePages”>     <script type=”text/javascript”>         document.getElementById(“s4-ribbonrow”).style.display = “block”;     </script> </Sharepoint:SPSecurityTrimmedControl>

5)      Save the new master page and publish it.

Reference:http://blogs.msdn.com/b/zwsong/archive/2010/04/29/how-to-hide-ribbon-from-users-without-edit-page-privilege.aspx

Sharepoint Unexpected Error

Click site action-> site permission get An unexpected error has occurred

Here are the full logs:

12/16/2011 12:59:29.10 w3wp.exe (0x11B4) 0x15C4 SharePoint Foundation Monitoring nasq Medium Entering monitored scope (Request (GET:http://8807ws01:80/_layouts/user.aspx))

12/16/2011 12:59:29.10 w3wp.exe (0x11B4) 0x15C4 SharePoint Foundation Logging Correlation Data xmnv Medium Name=Request (GET:http://8807ws01:80/_layouts/user.aspx) 3c0b3d6b-bc91-407f-9a55-12f4813a6825

12/16/2011 12:59:29.10 w3wp.exe (0x11B4) 0x15C4 SharePoint Foundation Logging Correlation Data xmnv Medium Site=/ 3c0b3d6b-bc91-407f-9a55-12f4813a6825

12/16/2011 12:59:29.18 w3wp.exe (0x11B4) 0x15C4 SharePoint Foundation Runtime tkau Unexpected System.NullReferenceException: Object reference not set to an instance of an object.    at Microsoft.SharePoint.ApplicationPages.UserRoles.InitPage()     at System.Web.UI.Control.LoadRecursive()     at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) 3c0b3d6b-bc91-407f-9a55-12f4813a6825

12/16/2011 12:59:29.19 w3wp.exe (0x11B4) 0x15C4 SharePoint Foundation Monitoring b4ly Medium Leaving Monitored Scope (Request (GET:http://8807ws01:80/_layouts/user.aspx)). Execution Time=89.9224 3c0b3d6b-bc91-407f-9a55-12f4813a6825

0. The third day still has no solution for it. It is time to do something big.

1.Get hint from internet, tell me find the back uped database, could be corrupted.

2. Go central management, try server back up, failed, get multiple recommmandation to upgrade databse.

3.  Go to management shell, Run PSConfig.exe -cmd upgrade -inplace b2b -force -cmd applicationcontent -install -cmd installfeatures.

4. Recall I have tried to upgrade server to Enterprise but I don`t have Enterpise Certificate, and it was stopped halfway, could be related.

5. go to site permission again, problem still there.

6. So I have to back up whole website and prepare to start again.

7. The most important part is my subsite, so i use those backup and restore->Granular Back up->export a site or list to back up my subsite first.

or.

stsadm -help export

[stsadm -o export -url URL -f filename]

stsadm -help import

[stsadm -o import -url URL -includesecurity]

8. I have also backed up my customized templates.

9. Now I need back up several pages I have done manually.->9:18 AM

10.9:32 delete site.

11. Uninstall sharepoint 2010. Retart.

12. ReInstall 10:06Am.

13. reinstalled 10:45AM.

14. Restored coreV4.css and v4.master. the Problem reappeared. Change back the v4.master, problem disappeared. So it is the V4. Master!!!

15. Problem Solved. Now I need to restore the whole site!!!

16. Go to sitecollection, open publish feature for site collection and site.

17. Go to general settings of application management, change person name actions to no, browser file handling to permissive, recycle bin to off. ok.

18. Go to manage Farm Features->deactive social tags and Note Board Ribbon Controls Feature.

19. Central Administration->Security->Autentication Providers->Default->Edit Autentication->Enable Anonymous access. Save.

20. copy v4.master and rename it. Design again.

21. import the subsite I backuped->11:18Am

22. Change maximumDynamic DisplayLevels=”5″; under new master template.

23. Change Corev4.css to customize my menus

.s4-tn li.dynamic > .menu-item{

display:block;

padding:3px 10px;

white-space:nowrap;

font-weight:normal;

color:white;

}

.s4-tn li.dynamic > a:hover{

font-weight:normal;

/* [ReplaceColor(themeColor:"Light2-Lighter")] */ background-color:#00a18f;

text-decoration:underline;

}

Sharepoint website customization notes

LEASE  do use firebug when you try to decode the sharepoint template!

Customization Corev4.css-

and if you can`t find the part from corev4.css, which could be saved in server at C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\template\layouts\1033\STYLES.

ms-rteElement-H1B   =   Headline of each document page

ms-quickLaunch{padding-top:5px;} = quicklaunch navigation

.s4-ql ul.root > li > .menu-item = the first navigation root

.s4-ql ul.root > li > ul >li > .menu-item  = the second quick launch root

.s4-ql ul.root > li > ul >li > ul> li > .menu-item  = the third quick launch root

body #s4-leftpanel-content= left side body border

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\template\layouts\1033\STYLES

CSS line 6994

.ms-rte-layoutszone-inner

{

word-wrap:break-word;

border:0px solid transparent;

margin:0px;

padding:10px;

overflow:hidden;

}

SearchBar:

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\1033\STYLES\Themable\SEARCH.CSS

.s4-search input.ms-sbplain =search input column

sharepoint 2010 not playing flash

SP2010 has restrictions on displaying SWF files. You need to go to central administration and check the “Browser File Handling” to “Permissive” for that web application’s general settings.

Sharepoint 2010 no navigation under look and feel

1.If you are not at the root of your site, under Site Collection Administration, click Go to top level site settings.

2.On the Site Settings page, under Site Collection Administration, click Site collection features.

3.On the Site Collection Features page, next to Office SharePoint Server Publishing Infrastructure, click Activate. Now the navigation link should show up under look and feel.

Sharepoint - Delete Corrupted SubSite

From sharepoint powershell console

stsadm -o deleteweb -url <websiteURL>

Sharepoint Crawling - Access is denied

Access is denied. Verify that either the Default Content Access Account has access to this repository, or add a crawl rule to crawl this repository. If the repository being crawled is a SharePoint repository, verify that the account you are using has “Full Read” permissions on the SharePoint Web Application being crawled. Solution Tried,
1. Go to command window and type regedit.exe
2. Once opened the registry editor, just navigate to “HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa“
3. Right click on “Lsa” and create a new 32bit DWORD value
4. Rename it as “DisableLoopbackCheck” (Note: you cannot rename it actually. so, once created the DWORD value, directly paste/type as “DisableLoopbackCheck”.
5. Then again modify the value of “DisableLoopbackCheck” as “1″
6. Close the registry editor. 7. Now start to crawl the content.

Sharepoint 2010 Customize Survey Form

The default Sharepoint Survey template sometimes can be anoyying,
1. You cant add plain Text on it. So if you want to add some introduction or summary, or some additional reference information. It will be really struggling
2. The question and answer are in fixed format, you cant insert a picture or anything cusmoized on it.
Spent couple days on this, Searched alot website and finally got it works on my website. Suprisely it is fairly easy.
Solution:
1. On sharepoint designer 2010, go to the Lists and Libraries on left panel, Find the survey you are looking for. Open it.
2. Click New at the Forms Panel on the right side, type in the <New Form Name>, check "set as default form for the selected type", check "create link in list Item Menu and Ribbon", also type in the "link and Command Name", I.E. <New Survey>. Click OK.
3. Now click on the new form you just created to open it. It may take a bit time. Make sure you select split view under view. Make it easier for you to edit it.
4. By default, the new form is using Cutomized Form View, so we can easily create another table between "cancel" button and <question 1>, and start customizing the table here. You can insert pictures if you want and add any personal css code into the table.
5. To move the answers you just need find the current answers, remember select both lines of the code. I.E.






 Cut them and paste it into wherever you want the answer listed.
Save it.
Now when people click on Respond to this survey, they will see the form you just created other than the default one, Cheers!

Sharepoint 2010 URL not valid when upload file

Check the database size of WSS_CONTENT and found it is full.
Default is 4.096 Gb even you installed SQL standard. If you try to increase the file size it will tell you the license reach its limits. Even you have sql server standard installed.
The reason is by default it used express sql other than the one you installed.
Upgrade sql express node by use sql server installation disk and the problem resovled.

Sharepoint not showing calender content on internet but ok in Intranet

We have a ISA server in between the Sharepoint and internet. and For 2 years, I could not resovle this mystery problem, the Calender shows nothing on external network but working perfectly internally.

After 2 years, I accidentally found an post regarding the Menu Navigation not working on External network but internally.
http://blog.blksthl.com/2013/12/16/fixing-the-scriptresource-axd-errors-500-internal-server-error/

Since my gate is ISA 2006, which is old, however I found the similar area under
Configuration -> Add ons->Compression Filter -> Enalbed.
Bang! Problem solved.

Also the navigation dropdown which was blocked for last 2 years was solved as well.
Thank you so much
Thomas Balkeståhl
who is the author of
http://blog.blksthl.com/2013/12/16/fixing-the-scriptresource-axd-errors-500-internal-server-error/

SCCM 2012 TFTP download abort

When start system, the pxe is working, then within a second, it says download abort pxe then quit pxe booting.
This happens randomly.
to Fix this.
1. Make sure you have deployed the task sequence to All system/ Unknown devices.
2. On SCCM Console, Go to "\Assets and Compliance\Overview\Devices\All Systems" and find "Unknow" device, delete it. Then update members.
Try it again. This time it should be ok.

SCCM 2012 WDS cant be installed

WDS cant be installed  Failed ServerManagerCMD.exe -i WDS -a~

As suggested, the SCCM should install WDS when you check "Enabled PXE support" on PXE tab of Distribution Point Properties and you should not need to install WDS yourself.
In my case, it does not work on my windows server 2012. So here is the solution to fix it.
1. Uncheck "Enabled PXE support" on PXE tab of Distribution Point Properties.
2. Install WDS through Server Manager.
3. Start WDS and configure it to create C:\remoteInstall folder, and start the WDS after configuration.
3. Go back to SCCM console and "Enabled PXE support" on PXE tab of Distribution Point Properties again.
It works in my case.

And also After a lot test, it turns out most likely it is because my Windows 2012 is standard verison, after installed SCCM 2012 on Windows 08 Enterprise, no such error happens again.

SCCM 2012 Program Files cannot be located

Failed to run Task sequence
The task sequence cannot be run because the program files for XXX00001 cannot be located on a distribution point.
For more Information, contact your SystemAdministratororHelpdeskOperator.

It turns out, I have to created a boundary group under Boundary Groups and add the two servers into it. After that, the OS started deploying.
Reference:
http://social.technet.microsoft.com/Forums/en-US/949574ac-c947-4ff4-a817-263014246ee2/osd-failed-package-cannot-be-located-on-distribution-point

SCCM 2012 CheckList

he installation guide I choose is:
http://www.google.com.au/url?sa=t&rct=j&q=sccm%202012%20installation%20guide%20it%20notes&source=web&cd=1&cad=rja&ved=0CCoQFjAA&url=http%3A%2F%2Fmsfttech.blogspot.com%2F2012%2F03%2Fsccm-2012-installation-guide.html&ei=4Lg7Ut2CDsXtkgWDsoGwDA&usg=AFQjCNFibKLQVwBTwgfB_OAgK5dTtaplEg
It is almost perfect, however there are several thing you need check druing or after installation
1. If you see warning about SQL server checking area, dont forget to go to SQL server, add SCCM console computer as new user on SQL database. To do it you need use SQL management studio, users, new, domain-name\computername$, that way you can add computer name as a new user.
2. If you are using SQL 12 as the database, the report function wont work(when you click Create Report under Monitoring\ Overview\Reporting\Reports, you will get error Could not find an installed Reporting Services point. Verify the site role is installed and accesible.".
report
You need upgrade your SCCM 12 into SCCM 12 SP1. Instructions are here:
http://support.microsoft.com/kb/2801416
Remember, the Windows Assessment and Deployment Kit (ADK) for Windows® 8 is over 3G. So you better download it before you plan to install SCCM. SP1 update package is about 900Mb, you need download it as well.
3. Also in the installation guide it mentioned to install SQL cumulative updates, you better do it.

Clean Up SCCM client

I have installed the other SCCM server before, which installed the clients in all devices. Now I have installed a new SCCM server, the server can detect the devices and knows the SCCM clients are installed on devices. However, the The remote control and Remote Client greyed out
1. The remote tools are enabled on default settings.
2. installed remote assistant feature, it is the same.
3. installed Remote Access role, it is the same.
I suspect it may be because of the old client. So lucky I have one server with no client installed. Install client on that one. and the Remote Control is enabled on that one.
So I have to find a way to uninstall all the clients.
To do this, I need the report function on SCCM 2012, however there is a problem to have it on SCCM 2012. I need to install SCCM 2012 SP1. While I am waiting. I use an IP scan tool to get certain range of Computer names and starting uninstall the client with following method.
1. Download PSEXEC tool.
http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx
2. Download CCM lean tool.
http://www.microsoft.com/en-us/download/details.aspx?id=18153
REMEMBER, DONT RUN CCMCLEAN ON YOUR SCCM SERVER, IT WILL DESTROY YOUR SCCM SERVER!
3. Once installed Systems Management Server 2003 tool kit, share its installation folder to give read access to everyone.

4. Copy psexec to system32 folder under your windows folder. So you can run it anywhere.
5. Create your Computer Name CSV. with All the computer with previous SCCM client on it.
6. Create a dos batch as following:

for /f "tokens=1 delims=, " %%d in (.csv) do  (
psexec \\%%d -u  -p  \\\ccmclean -q -d
)
7. Run the dos command and the clients will be uninstalled.

SCCM 2012 Error 0x80004005 and 0x87d00215

Scroll down to conclusion if you dont have patience like me

Have tried:
1. Reinstall MP
2. Reinstall DP
3. Add .exe exception to IIS
4. Add POST verb to IIS.
5.Continue-
Check logs of IIS
find ipv6
disable ipv6
6.
Change the boundary ip to IP ranges.
7. Had a look of IP address again, found the IIS isnt right. Fix IIS. Re-install.
8. Progress:
This time only one error.
<![LOG[Failed to get DP locations as the expected version from MP 'http://<ServerName>. Error 0x87d00215]LOG]!><time="08:42:10.528-660" date="02-25-2014" component="ccmsetup" context="" type="2" thread="6240" file="ccmsetup.cpp:11261">
9. FOllowing this:
http://adminsccm.blogspot.com.br/2013/06/failed-to-get-dp-locations-as-expected.html
Even I cant read it. I look at the picture and focus on Client Package. Then I realize it is greyed out. Now.
10.
Fixed. THere are 2 things I have done. Not sure which one is the right one. However IF you do the both, I believe 0x87d00215 can be gone as well.
A.Created a update client package from defination. Under Software Library->Application Management->Packages.
B. Make sure boundary group has only 1 item, I got 2. 1 is active directory, the other is IP range. I deleted the AD group.
---------------------------------------
Conclusion:
---------------------------------------
If the client pushing is not working. You need go to client and do a manual install.
at client computer, run \\<sccmServer>\\SMS_<SiteCode>\bin\i386\CCMsetup.msi.
then go to client\C:\windows\CCMsetup\logs and check its log.
For
GetDPLocations failed with error 0x80004005
Fix: make sure you can contact the site address within the log. To do this go to IE, then copy the adderss of http://... to it and see if it is working. You may need:
1. Add .exe exception to IIS
2. Add POST verb to IIS.
3. Also need check the binding of the site name.
For Error 0x87d00215
1.Make sure boundary group is simply and correclty configured. Just create an IP ranged boundary then re-install DP from roles.
2.Created a update client package from defination. Under Software Library->Application Management->Packages.
Hopefully it helps.

SCCM 2012 Failed to register bgbserverchannel.dll

Update 06/05/14.
Still Check the Server version see if it is Enterprise.

At some stage you will find the the critical status of your roles, and which lead you to check logs of Bgbsetup.log, then you find the error message like this:
CTool::InstallManagedAssembly: Failed to register C:\Program Files\Microsoft Configuration Manager\bin\x64\microsoft.configurationmanager.bgbserverchannel.dll with .Net Fx 4.0

Here is the workaround for this one:
Go to  <C:\windows\Microsoft.NET\Framework64\v4.0.30319>

Make a backup copy of these files
InstallUtil.exe.config
RegSvcs.exe.config

Edit the original files by adding the following under the configuration node:
< runtime>    
    <loadFromRemoteSources enabled="true"/>
< /runtime>
NOTE: If you are not allowed to do so due to rights, right click on the file, property, change the ownership to domain admins. Then you can edit them.
Then go to C:\windows\Microsoft.NET\Framework\v4.0.30319
do the above steps again.
Then re-install the role, and look at the Bgbsetup.log again, you should be able to see it is installed successfully.
REF:
http://www.windows-noob.com/forums/index.php?/topic/7401-sms-notification-server-failed-critical-sccm-sp1-sql-2012-sp1/

SCCM 2012 Add Boot Image Error

Failed to make a copy of the source WIM file due to error 5
Update 06/05/14
Before Check anything, make sure you have Windows Enterprise as the server for SCCM 2012.
Also make sure the ADK 8.1 is installed from Internet. Sometimes, the file you downloaded get corrrupted so it is safer to install it from Microsoft Directly.


Check the logs of \\<server>\sms_<sitecode>\logs\SMSProv.log
Found:
Failed to copy \ to \\<server>\DS\Boot\{B37696A0-AA4E-4A6D-ADE6-5ABC57CC1A04}.wim. Error code = 5 SMS Provider 2/26/2014 2:04:24 PM 5100 (0x13EC)
Make a new share and make a new security make sure user has full access to it.
Copy the wim to it and add it again.
Works for me.

MP has rejected registration

Error: MP has rejected registration request due to failure in client certificate

Go to following areas and change them 1 by 1, since we are not using certificate in domain I change all the settings to HTTP instead:
1. Administration
->Site configuration - >Sites:Properties->Client Computer Communication:
Check Https or HTTP
Uncheck rest
2.Site configuration -> Servers and site system roles->Cm server->
-> Application catalog website point->properties
Allowed connections:HTTP
ok
3.->Distribution Point->properties
General
Http checked
All clients to connect anonymously checked
OK
4. ->Management Point-> Properties
General
Client Connections:
HTTP Checked
OK
The mistake I made was didnt check Http during installation. Now I have to do this all manually.
It works for me.

Administrative Rights on Server

When you try to locate your database to a sql server 2012 and windows 2012, you will get this error:
SCCM Prerequisite checking fail of administrative rights on server

So get a windows 2008 and sql 2008 for your database.

Update: 06/05/14
After a lot tests on different server and combinations. I believe it is more about what version you have for windows. It seems Enterprise version of windows works fine. Since I only got Windows 2012 Standard and multiple issues with it. And after move it to Windows 2008 Enterprise, all the problems disspeared. I dobt if the Windows Standard support SCCM 2012.
Contact Lei

SCCM 2012 DISM Cannot Find Path Specified

Uninstall ADK 8.1
Download ADK from Microsoft and reinstall. Problem Solved.

SCCM 2012 Installation and Configuration Notes

SCCM Installation TIPS:
1. install sql 08 on windows 08 server - enterprise, get all the updates for sql as well.
2. Install sccm 2012 on windows 08 server - enterprise - get all the updates. Install ADK 8.1. Install KB2905002.
3. start all discovery from ->Administration->Overview->Hierachy Configuration->Discovery Methods, enable all discovery.
4. Create Boundary Group and Boundary under same location( Administration->Overview->Hierachy Configuration)
5. Add the bondary group to Distribution Point from Administration->Overview -> Distribution Points -> properties->Boundary Groups
6. Install application catalog and web service in cm server, install reporting role on sql serve from Administration->Overview->Site Configuration->Servers and Site System Roles.
7. change client settings - computer agent -Default Application Catalog to cm server and add default app catalog to trusted zone.
8. Administration -Site Configuration -Sites -Site-(ON Top) Settings-> configure client installtion to push to all clients.
9. Configure Network Access Account -> Administration->Overview->Site Configuration->Sites->Right Click->Configure Site Components->Software Distribution->Network Access Account

SCCM OSD TIPS:
0. Always apply the image directly other than download by go to options, Task sequence options, access directly.
1. Import Image and make sure upload it to DP by distribute it to DP. Also under properties check copy it to DP.
2. Create Task sequence.
3. Create Collection of Computers and add Collection variable for example RoomName
4. Use Task Sequence Variable RoomName as Condition for different OSD in same task sequence.
5. Also you can use IsLaptop, IsDesktop or IsVirtualMachine as Condition for task sequence.
6. For rename computer, using different condition and put text into .wsp and copy it to DeploymentShare$,create MDT package by integrate MDT first then create it by point it to MDT deployment share folder.
7. In task sequence deploy the MD Package first then run gather before you setup task sequence.
8.following wsp scripts can be used:
<job id="BSCRenameComputer">
<script language="VBScript" src="/ZTIUtility.vbs"/>
<script language="VBScript">
Dim ComputerName
ComputerName = InputBox("Please type in Computer Namae.","Rename Computer",,,0)
oEnvironment.Item("OSDComputerName") = Ucase(ComputerName)
</script>
</job>
9 Put it under MDT deployment Share then upgrade the MDT package, otherwise the scripts wont be copied to server.
10. To run BAT or EXE, copy them to a network location and share them, then add connect to network folder step and run them from network folder.
For example connect \\cmserver\source\scripts to W:. And make sure all your scripts point to w:\. For example w:\LenovoSetupComplete.CMD.



SCCM WSUS Integration TIPS:
1. Install WSUS on window 2008 server, I install it on SCCM server
2. Install following updates:
Checking for supported version of WSUS (min WSUS 3.0 SP2 + KB2720211 + KB2734608) SMS_WSUS_CONFIGURATION_MANAGER 4/15/2014 2:48:40 PM 3648 (0x0E40)
3. Install Software Update role.
4. Start Sychronization under SOftware. Check WCS.log to see.

Compare with MDT,WDS,WSUS

Today I want to share some experience about SCCM.
I was using WDS for last 3 years and MDT sometimes only for MACS.
Recently I finally successfully deployed SCCM, and started use it. So far I found following benifits.
1. Deployment is much more flexible and no need to create deployment or boot image each time for different needs. Compare to WDS.
WDS is quick. HOwever whenever there is a little change on the client side, you need either update the boot image or install image, it is not very complex however it is time consuming, especially when you want to change your scripts under setup, you need do this.
On SCCM, you can seperate the scripts and image, and add the scripts into task sequence steps. So everytime if you need change the scripts, only change it on scripts itself. Save you a lot time.
2. Windows update is integrated.
When there are updates , you need update it with WDS mannually, which is time comsuming and repeatitive. Restart, APply updates, Quit domain, SYSPREP...
With SCCM, one task sequence with deploy and capture, everything is automatic. You only need run this once a month and dont need worry about update system mannually since it will do it for you.
3. Software deployment.
Software deployment is really flexible with SCCM, you can deploy it ondemand, with OSD or with Software Centre, you can force the installation or direct user to install it on request. with WDS you have to do it mannualy or by scripts, or through LUP which take a lot time to build the updates.
4. Remote control or assistant
By Remote tools, you can help user use SCCM console, you can do this manually however with the console, it is a lot convenient since all the devices are listed in one location, you dont need manage anything.

SCCM 2012 Can Not Add Image

Recently I am trying to fix one problem os SCCM 2012 R2 so I reinstalled it couple of times, however It brough me more problems.
This wasnt happening first time, now I cant get it right. The problem happens when you add boot image and it tells you:
The add Boot Image Wizard complete with errors.
Error: Data Source Information
Source location: \\8807cm\Share\WIm\Win8.1\64\boot.wim
Boot Image: 1 - Microsoft Windows PE (x64)
 Error: Package Information
Name: boot
 Error: Errors
The specified file can not be imported. Make sure the file is not read only and you have read and write access to it.

Check log : \\<Server>\SMS_<CODE>\Logs\SMSProv.log, I found this:
ERROR> failed to mount wim file err=3 SMS Provider 3/12/2014 8:11:46 AM 1900 (0x076C)
*~*~e:\nts_sccm_release\sms\siteserver\sdk_provider\smsprov\sspbootimagepackage.cpp(3766) : Failed to insert OSD binaries into the WIM file~*~* SMS Provider 3/12/2014 8:11:47 AM 1900 (0x076C)
*~*~Failed to insert OSD binaries into the WIM file ~*~* SMS Provider 3/12/2014 8:11:47 AM 1900 (0x076C)

I couldnt resolve it yestarday however When I woke up this morning I realized something I missed could cause it, the MDT integration tool. SOunds reasonable right? Lets Install the MDT integration tool now.
Solution:
First download MDT 2013 from microsoft then follow this beutiful article:
 http://geekswithblogs.net/Wchrabaszcz/archive/2013/11/12/sccm2012-r2--how-to-integrate-mdt-with-sccm.aspx
In short quickly start DeploymentWorkben and go to COmponents, find Windows Automated Installation kit(x64) and (x86), download both.
It may take a while.
Once the components are downloaed and installed.
Create a new Deployment Share, Once finished go to Configure ConfigMgr Integration and finish it.

Eventually I found it is all because the Server Version of Windows 2012 is standard not enterprise, which caused all the hassle. After reinstall SCCM 2012 R2 on Enterprise version of Windows. Problem gone.

SCCM 2012 Serial Number Report

Just for my reference, I choose to write this article to give myself a quick solution for my future Reporting Configuration.
Part 0.
Enable Hardware inventory through Client settings -> Default settings.


Part 1:
Install Reporting Service Role:
1. Go to Administration->Server and Site System Roles-> Right Click on your DATABASE server, add Site System Roles->
General->Next>Proxy>Next> System Role Selection > Choose Reporting Service Point >next....

Part 2. Configure Reporting.
1. Open IE as Administrator, type in Http://<DatabaseServerName>/Reports
2. Put your mouse over The site Code, From the Dropdown list Select Security.
3. Add the report Users/Group by use New Role Assignment.
4. Once finished, Edit, and give all access to the user.
5. Dont leave this page. Since we can build a report in next step.

Part 3. Build a customized report with Comuter Serial Number
1. From the same page or click Home to the SQL server Reporting Services page,(You can do this through Console as well.) Click Report Builder.
2. New Report -> Table or Matrix Wizard ->
3. Choose a dataset -> Create a Dataset -> Next
4. Choose the default data source and test Connection, next -> Edit as Text
5. Copy Following and paste it to the Text Area
Select 
sys.Name0 Machine, CS.UserName0 'User Name',OS.Caption0 OS, OS.CSDVersion0 'Service Pack',CS.Manufacturer0 Manufacturer,CS.Model0 Model,BIOS.SerialNumber0 'Serial Number',RAM.Capacity0 Memory, cs.SystemType0
 From 
v_R_System SYS,v_GS_COMPUTER_SYSTEM CS,v_GS_PC_BIOS BIOS , v_GS_OPERATING_SYSTEM OS, v_GS_PHYSICAL_MEMORY RAM 
 where 
sys.Name0=cs.Name0 and sys.ResourceID=OS.ResourceID AND sys.ResourceID=ram.ResourceID 
and sys.ResourceID=bios.ResourceID
  --Where 
sys.Name0 = @variable 
and 
order by sys.Name0
6. Run by click F5 or Exclamation Mark, See if there are results. If there are not much, it is because you dont have too much records yet, wait couple of days there will be more.
7. Next, Drag all the fields to Vlaues -> Next
8. Next-> Select Style -> Next -> Finish
9. You can customize other area by use tools above the field, it is like word. So you can insert title or picture or background.
10. Save and Close it.
11. After save it on the root location , refresh the home page, you should see the page is there, click it you can view the report online.
Cheers.




Reference:
1. Enable Hardware Inventory.
http://technet.microsoft.com/en-us/library/hh301103.aspx
2. Installation and Configure Reporting
http://www.windows-noob.com/forums/index.php?/topic/4550-using-sccm-2012-rc-in-a-lab-part-11-adding-the-reporting-services-point-role/
3. SCCM 2012 Reporting: Get system serial number & create custom SSRS report
http://blogs.technet.com/b/infratalks/archive/2013/09/10/sccm-2012-reporting-get-system-serial-number-amp-create-custom-ssrs-report.aspx

SCCM 2012 Endpoint Protection updates

READ GROUP POLICY CONFIGURATION ONLY YOU CAN ONLY GET WINDOWS UPDATE BUT NOT ENDPOINT UPDATE

This is about one branch of Software update under SCCM 2012, I will not mention all the standard procedures of Software Update installation since you can follow this beautiful article from:
http://www.windows-noob.com/forums/index.php?/topic/4467-using-sccm-2012-rc-in-a-lab-part-6-deploying-software-updates/
however I will talk about several things not listed on that article and without those minor changes you wont get your client `s Endpoint protection updated.
1. About WSUS and SCCM 2012 Sychronization,
I found it is impossible to get the updates downloaded into the specified location when you create update packages and after some research I found You can only download those from Microsoft directly other than any location you specified or local update server, in my case it is from a centralized location in education network. So it is funny you can sychronize from one server and still need download from Microsoft.
To chose what you need download and how to download them you need go to:
UPDATE CONFIGURAITON
SCCM Console -> Administration -> Sites-> Configure site components -> Software update point ->
To download update for Endpoint protection ONLY, I choose ->  Classification Tab -> Defination Update and Update, Product Tab -> ForeFront - > Forefront Endpoint Protection 2010,
this will allow you to have Forefront updates downloaded to your SCCM server, however I believe you need also choose windows 8.1 updates but it is not related here.

PROXY CONFIGURATION
So if you are using proxy to browsing internet, you need create a agent to download those updates. To do this, go to:
1. SCCM Console -> Administration -> Server and Site System Roles -> Software Update Point (Right Click)-> Proxy and Account Settings -> Check both
2. SCCM Console -> Administration -> Server and Site System Roles -> Site System (Right Click)-> Properties -> Proxy -> here to add your proxy and make sure they are correct.

COMPUTER ASSET CONFIGURATION
I am applying this Endpoint protection to all systems however If you want create certain type of OS collection, I will introduce a little here.
For example to create a Windows 8 Auto Incremental Collection you need go to :
Asset and Compliance -> Device Collection -> Create New Collection -> Direct Rule ->
Resource Class : System Resource
Atrribute Name : Operating system name and version
Value : Microsoft Windows NT Workstation 6.3
Enable auto encremental updates : yes

So you can have your windows 8.1 collection ready for apply windows 8.1 windows update only



GROUP POLICY CONFIGURATION:
Remeber: there should be no group policy configured for windows update at all, and configure it under client settings.
However, for Endpoint protection you need add the registry of Microsoft update option otherwise you can only get windows update and will not get endpoint update.
To configure windows update, make sure you clear all the settings for WSUS or anyother update solutions you used in GPO before. And let SCCM Client to handle it.
For Endpoint Protection, you need check the "Give me updates for other Microsoft products when i update Windows" under windows update settings, to do this through GPO (actually GPP)
Please read my other article :
http://www.itlei.com.au/index.php/microsoft/active-directory/auto-generate-from-title-17
to check if update is successful or if there are things going on the client, go to :
Client machine -> %SYSTEMROOT%\WindowUpdate.log

DEPLOYMENT PACKAGE CREATION:
Software Library-> Software Update -> Automatic Deployment Rules ->  Creat ...->
Software Update Tab -> Product : Forefront Endpoint Protection 2010, Update Classification: Defination update or Updates ,
Evaluation schedule Tab: (Depend on your needs, for me 7 days),
Deployment Schedule Tab : ASAP,
User Experience Tab: Hide in Software Center and all notifications ,
Deployment Package : Create package and make sure it is auto incremental

Hopefully those information can get you through. Cheers.

SCCM 2012 Task Sequence Password

1. I learnt this because I need deploy image without user interaction however I have to make sure put security on other OSDs, so this comes up. I googled a lot and finally come up one solution for myself with some area google not covered.
2. You have to use a Boot Image from Windows Installation Disk to support HTA, I tried the default image from SCCM, didnt work.
3. Import the Windows 8.1 boot.wim from Windows 8.1 64bit installation disk. Add HTA support from Other Compomnents under properties, deploy it to PXE and distribute it to DP.
4. Create a custom Package on network share, put all your custom scripts and hta in it and create package from SCCM 2012, when create package, choose this package contains a source folder, nominate the share to it. I call my package HTA.
5. For this task, we need two scripts.
5.1 : Password.hta



Prompt for password











5.2 Shutdown.WSF

  


6. Put the two files under the share, also copy your site`s ico to the same folder, update the distribution.
7. At your current task sequence, before the task sequence started , for me I add it before format disk, add a group called validation:
Under validation create following tasks:
7.1. Setup Task Sequence Variable (Set your password)
Task Sequence Variable: Password
Value : <yourPassword>
7.2 Run Command Line (Get password and authenticate with your password set in 7.1)
Command line: Password.hta
Package:
HTA
7.3 Run Command Line (Decide shutdown computer or not based on Authencation in 7.2)
Command line: cscript.exe "shutdown.wsf"
Package:
HTA
8. This should help you to add Password Prompt for each task sequence and disable the password from PXE.

Reference:
http://www.petervanderwoude.nl/post/add-hta-support-to-a-boot-image-with-configmgr-2012/
http://www.windows-noob.com/forums/index.php?/topic/2336-password-protect-a-task-sequence/
http://social.technet.microsoft.com/Forums/systemcenter/en-US/84fb4914-21ca-4b9b-88ae-16a247551eb4/password-protect-task-sequence

SCCM 2012 OSD with no User Interaction

Look at my other post to add password protection in task sequence.
http://rockyoz.blogspot.com.au/2014/11/task-sequence-password.html
MAKE SURE YOU KNOW WHERE YOU DEPLOY THIS TO. 
BAD THINGS CAN HAPPEN IF you deploy OSD to any computer shouldnt be here. You may lose your job.

1. Make sure there is no PXE password in DP -> PXE.
2.Make sure the computers you need to re-image are in one Computer Collection, Double check this.
3. Deploy OSD to computers as required, ASAP.
4.Configure your computer can be WAKE ON LAN and boot from LAN when WAK ON LAN.
5. If AMT is not supported llike me, use shutdown command to shut computers remotely, and WOL command to start computer remotely. The computers should be started then boot into PXE SCCM OSD straight after.

SCCM 2012 Client Manual Windows Update Error : 0x80244022

Using SCCM to deploy WIndows update saved me a lot time. However I am running into this error when try to run windows update manually from CLient.
Error code is 0x80244022 and ask me to try again.

SO look into c:\windows\windowsupdate.log :
 

2014-09-16 09:49:48:664 1064 1a54 Misc WARNING: DownloadFileInternal failed for http://:8530/selfupdate/wuident.cab: error 0x801901f7
2014-09-16 09:49:48:664 1064 1a54 Setup WARNING: SelfUpdate check failed to download package information, error = 0x80244022
2014-09-16 09:49:48:664 1064 1a54 Setup FATAL: SelfUpdate check failed, err = 0x80244022

Copy and paste the http://<fullDomainName>:8530/selfupdate/wuident.cab address to internet browser and return error, so clearly Client can not communicate SCCM server WSUS 8530 to kick off the update evaluation.
So go to SCCM server and start IIS, go to WSUS administration site and right click it to change Site Bindings.
Under Host Name add * to listen all http title at port 8530, since there is only WSUS is using 8530 so there is no conficts to the other sites.
Run the windows update at client again, BINGO, you got 4 important update! Cheers!

SCCM 2012 WIndows 8.1 on MAC BootCamp

This is another article about windows on MAC, this time I am using SCCM 2012. And this is acctually a very quick steps.
1. To start, get those things ready:
1.1 Boot Camp package from MAC website. Find the right driver for you, download them before started.
1.2 Windows 8.1 installation disk.
1.3 SCCM 2012 Boot Media (Disk /USB)
2. First go to MAC Side, run BootCamp and make a partition. Remember the size of the partition. Choose I have already drivers and insert windows 8.1 installation disk to restart your computer.
3. In windows 8.1 installation boot up, choose Repair, Trouble shooting, advanced and open command line.
4. Run diskpart
select disk 0
list partition
select partition 3/4 (Based on partition size)
Format fs=NTFS Label="bootcamp" Quick
Assign letter = c
active
exit
5. In your SCCM server task sequence , copy a normal windows 8.1 installation task sequence, make sure you disable the task of Partition/Formatting and let installation OS choose next available formated partition. and deploy it to unknown systems and make it availabe to Media and PXE only.
6. Insert SCCM task sequence boot media, restart your computer and hold option to choose boot media. Choose the task sequence you just created.
7. Once installation finished. Manually run boot camp driver,  setup, it will install all apple drivers for you.

HAT Notes

1. Before you run your first HTA application, make sure you insert a restart computer with WINPE image that you loaded from windows installation disk. The inbuilt x64 or x86 boot image wont support HTA, which will cause fails to run your scripts.

2. To hide the current task sequence window in VBS:
Set oTSProgressUI = CreateObject("Microsoft.SMS.TSProgressUI")
oTSProgressUI.CloseProgressDialog
Set oTSProgressUI = Nothing

3. To show the task sequence window when you quit HTA window:
objOSD("ALLOWOSDBUILD") = "YES"
window.close()

4. To Set up a variable for your use through the whole task sequence, simply add a task variable in your task sequence.

5. To access that task sequence variable and any other :
Set objOSD = CreateObject("Microsoft.SMS.TSEnvironment")
objOSD("TaskType")="ReImageComputer"

6. Add task variables before HTA, set variable values use VBS then run tasks based on variable value by set up the task running conditions.

7. You can put all the css stylesheet and other pictures in ur customized HTA packages. Just like a html webpage.

Setup Computer Name

       


    

Create the wsb file as above and add task : cscript.exe "%deployroot%\scripts\BSCRenameComputer.wsf" into task sequence.