Sunday 21 December 2014

WMI Explained and How to use with .NET

WMI Explained and How to use with .NET

WMI is not new but as old as windows. WMI full form is Windows Management Instrumentation, which is basically an interface to the Windows OS system settings, drivers ,hardware.... .You can use wmi to intrograte windows system and servers along with network . WMI use scripting language like VnScript,JScript(not javaScript) to interact with windows.
Later microsoft integrated WMI namespace available in .NET. So, we  can use WMI with c#,vb.net(all language which work on .net)
A .NET developer can use WMI to obtain information about drivers installed on the client machine, verify whether the system is licensed or not, check for hardware information of each and every deveice and a lot more.
WMI is a very powerfull tool, and once you know how to get what you need, it can be invaluable as a time saver. When developing Windows applications, developers often need information a system, either local or remote, that although commonplace, can be very tough to get. There is using the remote registry, but I myself do not allow remote registry access as do many network admins. WMI is usually wide open on networks, assuming you have the required rights to query it .

WMI Architecture

The purpose of WMI is to present a uniform interface to any local or remote applications or scripts that need to access management data from a computer system, network or application. Thanks to WMI, programs do not have to talk to a wide variety of operating system APIs which can be particularly inconvenient for scripting languages.
All WMI interfaces are based on the Component Object Model (COM), however it is possible to access WMI from .NET thanks to the COM Inter-Op mechanism, as our diagram shows.




The main parts of WMI are as follows:
Managed objects and providers: A WMI provider is a COM object that monitors one or more managed objects for WMI. Like a driver, a provider extracts WMI data from a managed object and is responsible for passing messages from WMI back to the managed object.
WMI infrastructure: As a Windows component WMI consists of the Windows Management service, which includes the WMI Core, and the WMI repository. The service acts as an intermediary between the providers and the repository. Only static data about objects, such as the classes defined by the providers, are stored in the repository.
Management applications and scripts: A management application queries management information either by calling the COM API for WMI or through the Scripting API for WMI.
Assume you have to Query a database, you will choose SQL to query it likewise  we have WQL to Query a windows system
If you know the provider classes and the fields available, then you can get the info very easily.  For instance, if you wanted to get a list of logical drives from a system you would use the following query:
Select * from Win32_LogicalDisk
You can, however, refine the search by using where clauses and getting specific "fields" in the query. The following query gets the amount of freespace, the size, and the name of all fixed disk drives:
Select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3
As you can see, constructing a simple WMI query is quite easy.  To get results, you need and interface, and in .Net it is provided by the System.Management namespace.  To make it work all you need is a query, and a little bit of code, just as if you were querying a database.
Note : while starting working with WMI make sure you set refrence to system.management.instrumentation. namespace

What Is WMI Provider?

WMI Provider is a software component that functions as a mediator between the CIM Object Manager and managed objects. By using the WMI APIs, providers supply the CIM Object Manager with data from managed objects, handle requests on behalf of management applications, and generate event notifications.

Microsoft WMI Code Creator

The Microsoft WMI Code Creator application  here. once downloaded and ran locally,you will see below screen
 
 “The WMI Code Creator tool allows you to generate VBScript, C#, and VB.NET code that uses WMI to complete a management task such as querying for management data, executing a method from a WMI class, or receiving event notifications using WMI.”.I you will see below ,it generates code as per your choice
 
 CONTINUE....
Further readings http://msdn.microsoft.com/en-us/library/ms257353%28v=vs.80%29.aspx

Sunday 7 December 2014

Uploading and Importing CSV file to SQL Server using WebAPI


Uploading and Importing CSV file to SQL Server  using WebAPI

Assumption: Basic knowledge of MVC and WebApi
Download Source code:
Few weeks ago I was working with a WebAPI services . These services are consumed by multiple devices like IOS,Andriod....which involves uploading CSV file to Sql Server database and thought I'd share the simple implementation that I did on the project which i will believe will save somebodies time. In this post I will demonstrate how to create WebApi and upload and import CSV file to SQL Server database.

 Step 1: Create WebApi Service Application using your favourite IDE like shown below




Step 2:Modify Web.Config with sql connection details






Step 3: Modify UploadController with below class


public class UploadController : ApiController
    {
        [Route("api/Device/PostUpload")]
        [HttpPost]
        [ActionName("PostUpload")]
        public string PostUpload()
        {
            string individualExtractPath = null;
            StreamReader sr = null;
            try
            {
                HttpRequest request = HttpContext.Current.Request;
                //making file unique,you can use GUID also
                string fileName = request.Files[0].FileName + "_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");
                string DeviceId = request.Form["DeviceId"];
                //check for column key id
                if (DeviceId == null || "null".Equals(DeviceId.ToLower()))
                {
                   return "UnRegistered";

                }   
                string strFileExtractPath = HttpRuntime.AppDomainAppPath;
                strFileExtractPath = Path.Combine(strFileExtractPath, "UploadExtract");

                if (!Directory.Exists(strFileExtractPath))
                {
                    Directory.CreateDirectory(strFileExtractPath);
                }

                individualExtractPath = Path.Combine(strFileExtractPath, fileName);
                Directory.CreateDirectory(individualExtractPath);
                request.Files[0].SaveAs(individualExtractPath + "\\" + request.Files[0].FileName);
                string strUnzipedFilesLocation = Path.Combine(individualExtractPath, "unzipedFiles");
                Directory.CreateDirectory(strUnzipedFilesLocation);
                ZipFile.ExtractToDirectory(individualExtractPath + "\\" + request.Files[0].FileName, strUnzipedFilesLocation);
                ArrayList fileList = new ArrayList();
                // Get the files in the Directory
                string[] files = Directory.GetFiles(strUnzipedFilesLocation);

                int len = files.Length;

                for (int i = 0; i < len; i++)
                {
                    string filename = files[i];

                    // Add into the ArrayList
                    fileList.Add(System.IO.Path.GetFileName(filename));
                    FileInfo uploadFile = new FileInfo(filename);
                    sr = new StreamReader(filename);
                    DataTable oDataTable = null;
                    int RowCount = 0;
                    string[] ColumnNames = null;
                    string[] oStreamDataValues = null;
                    //using while loop read the stream data till end
                    while (!sr.EndOfStream)
                    {
                        String oStreamRowData = sr.ReadLine().Trim();
                        if (oStreamRowData.Length > 0)
                        {
                            oStreamDataValues = oStreamRowData.Split(',');
                            //Bcoz the first row contains column names, we will poluate 
                            //the column name by
                            //reading the first row and RowCount-0 will be true only once
                            if (RowCount == 0)
                            {
                                RowCount = 1;
                                ColumnNames = oStreamRowData.Split(',');
                                oDataTable = new DataTable();
                                //using foreach looping through all the column names
                                foreach (string csvcolumn in ColumnNames)
                                {
                                    DataColumn oDataColumn = new DataColumn(csvcolumn.ToUpper(), typeof(string));
                                    //setting the default value of empty.string to newly created column
                                    oDataColumn.DefaultValue = string.Empty;
                                    //adding the newly created column to the table
                                    oDataTable.Columns.Add(oDataColumn);
                                }
                            }
                            else
                            {
                                //creates a new DataRow with the same schema as of the oDataTable            
                                DataRow oDataRow = oDataTable.NewRow();
                                //using foreach looping through all the column names
                                for (int c = 0; c < ColumnNames.Length; c++)
                                {
                                    oDataRow[ColumnNames[c]] = oStreamDataValues[c] == null ? string.Empty : oStreamDataValues[c].ToString();
                                }
                                //adding the newly created row with data to the oDataTable       
                                oDataTable.Rows.Add(oDataRow);
                            }
                        }
                    }
                    //close the oStreamReader object
                    sr.Close();
                    //release all the resources used by the oStreamReader object
                    sr.Dispose();
                    //Creating two additinal columns dynamically because mobile trip file doesn't provide that

               
                    DataTable dtFinal = oDataTable;
                    //Class Bulk Insert here
                    BulkInsertTripFile(oDataTable);

                }

                return "File SuccessFully Posted";
            }
            finally
            {
                try
                {
                  
                    if (!string.IsNullOrEmpty(individualExtractPath) && Directory.Exists(individualExtractPath))
                    {
                        //If any such directory then creates the new one
                        DeleteDirectory(individualExtractPath);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        /// <summary>
        /// After uploading file ,just need
        /// </summary>
        /// <param name="target_dir"></param>
        private static void DeleteDirectory(string target_dir)
        {
            string[] files = Directory.GetFiles(target_dir);
            string[] dirs = Directory.GetDirectories(target_dir);

            foreach (string file in files)
            {
                File.SetAttributes(file, FileAttributes.Normal);
                File.Delete(file);
            }

            foreach (string dir in dirs)
            {
                DeleteDirectory(dir);
            }

            Directory.Delete(target_dir, false);
        }
        /// <summary>
        /// Method for Trip Detail bulk insert with datatable as parameter
        /// </summary>
        /// <param name="dt"></param>
        private void BulkInsertTripFile(DataTable dt)
        {

            string connString = System.Configuration.ConfigurationManager.AppSettings["BulkDemo"];

            // Copy the DataTable to SQL Server
            using (SqlConnection dbConnection = new SqlConnection(connString))
            {
                dbConnection.Open();
                using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
                {
                    s.DestinationTableName = "TripTable";
                    foreach (var column in dt.Columns)
                        s.ColumnMappings.Add(column.ToString(), column.ToString());
                    s.WriteToServer(dt);
                }
            }
        }
    }

step 4:Create view based on html page or you can create android or ios page for uploading/posting file
   
Hope this helps ... Shabir

Friday 28 November 2014

C# Important Code Snippets and Utility Function


      public static bool isValidEmail(string email)
        {
            bool flag;
            string MatchEmailPattern = "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?\r\n\t\t\t\t                [0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?\r\n\t\t\t\t                [0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";
            flag = (email == null ? false : Regex.IsMatch(email, MatchEmailPattern));
            return flag;
        }
        public static bool isValidURL(string url)
        {
            return Regex.IsMatch(url, "(http|https)://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?");
        }

       public static string[] LASTMONTH()
        {
            string[] dates = new string[2];
            DateTime dateTime = DateTime.UtcNow.AddHours(5.5);
            int year = dateTime.Year;
            dateTime = DateTime.UtcNow.AddHours(5.5);
            int month = dateTime.Month;
            DateTime lastDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);
            lastDate = lastDate.AddDays(-1);
            if (month != 1)
            {
                month--;
            }
            DateTime firstDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }
 
      public static string[] LASTQTR()
        {
            string[] dates = new string[2];
            DateTime dateTime = DateTime.UtcNow.AddHours(5.5);
            int quarterNumber = (dateTime.Month - 1) / 3 + 1;
            if (quarterNumber != 1)
            {
                quarterNumber--;
            }
            dateTime = DateTime.UtcNow.AddHours(5.5);
            DateTime firstDate = new DateTime(dateTime.Year, (quarterNumber - 1) * 3 + 1, 1);
            dateTime = firstDate.AddMonths(3);
            DateTime lastDate = dateTime.AddDays(-1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }
  
      public static string[] LASTYEAR()
        {
            string[] dates = new string[2];
            int year = DateTime.UtcNow.AddHours(5.5).Year;
            year--;
            DateTime firstDate = new DateTime(Convert.ToInt32(year), 1, 1);
            DateTime lastDate = new DateTime(Convert.ToInt32(year), 12, 31);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }
  
     public static bool SendEmail(string server, string AuthUser, string password, string subject, string from, string recipients, string body, string fileNames)
        {
            int i;
            bool status = true;
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient(server);
                mail.From = new MailAddress(from);
                char[] chrArray = new char[] { ',' };
                string[] strArrays = recipients.Split(chrArray);
                for (i = 0; i < (int)strArrays.Length; i++)
                {
                    string eachRecipient = strArrays[i];
                    if (!string.IsNullOrEmpty(eachRecipient))
                    {
                        mail.To.Add(eachRecipient);
                    }
                }
                mail.IsBodyHtml = true;
                mail.Subject = subject;
                body = HttpUtility.HtmlDecode(body);
                mail.Body = body;
                if (!string.IsNullOrEmpty(fileNames))
                {
                    Attachment attachment = null;
                    chrArray = new char[] { ',' };
                    strArrays = fileNames.Split(chrArray);
                    for (i = 0; i < (int)strArrays.Length; i++)
                    {
                        string eachAttachment = strArrays[i];
                        if ((string.IsNullOrEmpty(eachAttachment) ? false : File.Exists(eachAttachment)))
                        {
                            attachment = new Attachment(fileNames);
                            mail.Attachments.Add(attachment);
                        }
                    }
                }
                SmtpServer.Port = 25;
                SmtpServer.Credentials = new NetworkCredential(AuthUser, password);
                SmtpServer.EnableSsl = false;
                SmtpServer.Send(mail);
            }
            catch (Exception exception)
            {
                Exception e = exception;
                status = false;
                LogHandler.getInstance().Log(e);
            }
            return status;
        }
  
  public static string ArraytoString(object[] strArr)
        {
            string str;
            string str1;
            string returnString = string.Empty;
            if (strArr != null)
            {
                for (int i = 0; i < (int)strArr.Length; i++)
                {
                    if (strArr[i] == null)
                    {
                        str1 = null;
                    }
                    else
                    {
                        str1 = strArr[i].ToString();
                    }
                    if (!string.IsNullOrEmpty(str1))
                    {
                        returnString = string.Concat(returnString, strArr[i], (i < (int)strArr.Length - 1 ? "," : ""));
                    }
                }
                str = returnString;
            }
            else
            {
                str = null;
            }
            return str;
        }
  
  public static int getMonthsBetweenDates(DateTime startDate, DateTime endDate)
        {
            int count = 0;
            if (endDate > startDate)
            {
                int year = endDate.Year - startDate.Year;
                int month = endDate.Month - startDate.Month + 1;
                count = year * 12 + month;
            }
            return count;
        }
  
   public class PGUtil
    {
        private static WindowsImpersonationContext impersonationContext;

        public PGUtil()
        {
        }

        public static string[] AppendArrayElement(string[] array, object param)
        {
            string[] strArrays;
            if ((array == null ? false : param != null))
            {
                List list = array.ToList();
                list.Add(param.ToString());
                strArrays = list.ToArray();
            }
            else
            {
                strArrays = array;
            }
            return strArrays;
        }

        public static string ArraytoString(object[] strArr)
        {
            string str;
            string str1;
            string returnString = string.Empty;
            if (strArr != null)
            {
                for (int i = 0; i < (int)strArr.Length; i++)
                {
                    if (strArr[i] == null)
                    {
                        str1 = null;
                    }
                    else
                    {
                        str1 = strArr[i].ToString();
                    }
                    if (!string.IsNullOrEmpty(str1))
                    {
                        returnString = string.Concat(returnString, strArr[i], (i < (int)strArr.Length - 1 ? "," : ""));
                    }
                }
                str = returnString;
            }
            else
            {
                str = null;
            }
            return str;
        }

      

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = false)]
        public static extern bool CloseHandle(IntPtr handle);

        public static DataSet CreateDummyScalarDataSet(string columnValue)
        {
            return PGUtil.CreateDummyScalarDataSet(null, columnValue);
        }

        public static DataSet CreateDummyScalarDataSet(string columnName, string columnValue)
        {
            DataSet ds = null;
            try
            {
                ds = new DataSet();
                DataTable tbl = new DataTable();
                tbl.Columns.Add("Id");
                tbl.Rows.Add(new object[] { columnValue });
                ds.Tables.Add(tbl);
            }
            catch (Exception exception)
            {
                LogHandler.getInstance().Log(exception);
            }
            return ds;
        }

        public static int dateComparison(DateTime date1, DateTime date2)
        {
            return DateTime.Compare(date1, date2);
        }

        

        public static string FormatCSVstring(string inputString)
        {
            string str;
            string outPutString = string.Empty;
            try
            {
                inputString = PGUtil.escapeSpecialChar(inputString);
                string[] arrData = inputString.Split(new char[] { ',' });
                for (int i = 0; i < (int)arrData.Length; i++)
                {
                    string tempString = string.Format("'{0}'", arrData[i]);
                    outPutString = (i != 0 ? string.Concat(outPutString, ",", tempString) : tempString);
                }
                str = outPutString;
            }
            catch
            {
                str = inputString;
            }
            return str;
        }

        public static string FormatOracleDate(DateTime date)
        {
            string str;
            try
            {
                str = date.ToString("dd-MMM-yyyy");
            }
            catch
            {
                str = date.ToString();
            }
            return str;
        }

        public static string FormatSQLDate(string date)
        {
            string str;
            string str1;
            try
            {
                if (!date.Equals("NULL"))
                {
                    if (date == null)
                    {
                        str1 = null;
                    }
                    else
                    {
                        str1 = PGUtil.ToDateTime(date).ToString("yyyy-MM-dd");
                    }
                    str = str1;
                }
                else
                {
                    str = null;
                }
            }
            catch
            {
                str = date.ToString();
            }
            return str;
        }

        public static string FormatSQLDate(DateTime date)
        {
            string str;
            try
            {
                str = date.ToString("yyyy-MM-dd");
            }
            catch
            {
                str = date.ToString();
            }
            return str;
        }

        public static string FormatString(string formatString, params string[] values)
        {
            string str;
            if (!string.IsNullOrEmpty(formatString))
            {
                if (values == null)
                {
                    throw new ArgumentNullException("values");
                }
                for (int index = 0; index < (int)values.Length; index++)
                {
                    formatString = formatString.Replace(string.Concat("{", index, "}"), values[index]);
                }
                str = formatString;
            }
            else
            {
                str = formatString;
            }
            return str;
        }

        public static DateTime GetCurrentIndiaDate()
        {
            return DateTime.UtcNow.AddHours(5.5);
        }

        public static TimeSpan GetCurrentIndiaTime()
        {
            return DateTime.UtcNow.AddHours(5.5).TimeOfDay;
        }

        public static object GetDataFromSession(string key)
        {
            object returnValue = null;
            try
            {
                returnValue = HttpContext.Current.Session[key];
            }
            catch (Exception exception)
            {
                LogHandler.getInstance().Log(exception);
            }
            return returnValue;
        }

        public static T GetDataFromSession(string key)
        {
            T item;
            T returnValue = default(T);
            try
            {
                if (HttpContext.Current.Session[key] is T)
                {
                    item = (T)HttpContext.Current.Session[key];
                    return item;
                }
            }
            catch (Exception exception)
            {
                LogHandler.getInstance().Log(exception);
            }
            item = returnValue;
            return item;
        }

        public static int getMonthsBetweenDates(DateTime startDate, DateTime endDate)
        {
            int count = 0;
            if (endDate > startDate)
            {
                int year = endDate.Year - startDate.Year;
                int month = endDate.Month - startDate.Month + 1;
                count = year * 12 + month;
            }
            return count;
        }
 

        public static bool isValidEmail(string email)
        {
            bool flag;
            string MatchEmailPattern = "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?\r\n\t\t\t\t                [0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?\r\n\t\t\t\t                [0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";
            flag = (email == null ? false : Regex.IsMatch(email, MatchEmailPattern));
            return flag;
        }

        public static bool isValidURL(string url)
        {
            return Regex.IsMatch(url, "(http|https)://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?");
        }

        public static string[] LASTMONTH()
        {
            string[] dates = new string[2];
            DateTime dateTime = DateTime.UtcNow.AddHours(5.5);
            int year = dateTime.Year;
            dateTime = DateTime.UtcNow.AddHours(5.5);
            int month = dateTime.Month;
            DateTime lastDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);
            lastDate = lastDate.AddDays(-1);
            if (month != 1)
            {
                month--;
            }
            DateTime firstDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }

        public static string[] LASTQTR()
        {
            string[] dates = new string[2];
            DateTime dateTime = DateTime.UtcNow.AddHours(5.5);
            int quarterNumber = (dateTime.Month - 1) / 3 + 1;
            if (quarterNumber != 1)
            {
                quarterNumber--;
            }
            dateTime = DateTime.UtcNow.AddHours(5.5);
            DateTime firstDate = new DateTime(dateTime.Year, (quarterNumber - 1) * 3 + 1, 1);
            dateTime = firstDate.AddMonths(3);
            DateTime lastDate = dateTime.AddDays(-1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }

        public static string[] LASTYEAR()
        {
            string[] dates = new string[2];
            int year = DateTime.UtcNow.AddHours(5.5).Year;
            year--;
            DateTime firstDate = new DateTime(Convert.ToInt32(year), 1, 1);
            DateTime lastDate = new DateTime(Convert.ToInt32(year), 12, 31);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }

       
        public static string[] QTD()
        {
            string[] dates = new string[2];
            DateTime utcNow = DateTime.UtcNow.AddHours(5.5);
            int quarterNumber = (utcNow.Month - 1) / 3 + 1;
            utcNow = DateTime.UtcNow.AddHours(5.5);
            DateTime firstDate = new DateTime(utcNow.Year, (quarterNumber - 1) * 3 + 1, 1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            utcNow = DateTime.UtcNow;
            dates[1] = PGUtil.FormatSQLDate(utcNow.AddHours(5.5));
            return dates;
        }

        public static void ReDimArray(ref string[] sourceArray, int newLength)
        {
            if (newLength >= (int)sourceArray.Length)
            {
                string[] newArray = new string[newLength];
                for (int i = 0; i < (int)sourceArray.Length; i++)
                {
                    newArray[i] = sourceArray[i];
                }
                sourceArray = newArray;
            }
        }

       

        public static bool SendEmail(string server, string AuthUser, string password, string subject, string from, string recipients, string body)
        {
            bool flag = PGUtil.SendEmail(server, AuthUser, password, subject, from, recipients, body, null);
            return flag;
        }

        public static bool SendEmail(string server, string AuthUser, string password, string subject, string from, string recipients, string body, string fileNames)
        {
            int i;
            bool status = true;
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient(server);
                mail.From = new MailAddress(from);
                char[] chrArray = new char[] { ',' };
                string[] strArrays = recipients.Split(chrArray);
                for (i = 0; i < (int)strArrays.Length; i++)
                {
                    string eachRecipient = strArrays[i];
                    if (!string.IsNullOrEmpty(eachRecipient))
                    {
                        mail.To.Add(eachRecipient);
                    }
                }
                mail.IsBodyHtml = true;
                mail.Subject = subject;
                body = HttpUtility.HtmlDecode(body);
                mail.Body = body;
                if (!string.IsNullOrEmpty(fileNames))
                {
                    Attachment attachment = null;
                    chrArray = new char[] { ',' };
                    strArrays = fileNames.Split(chrArray);
                    for (i = 0; i < (int)strArrays.Length; i++)
                    {
                        string eachAttachment = strArrays[i];
                        if ((string.IsNullOrEmpty(eachAttachment) ? false : File.Exists(eachAttachment)))
                        {
                            attachment = new Attachment(fileNames);
                            mail.Attachments.Add(attachment);
                        }
                    }
                }
                SmtpServer.Port = 25;
                SmtpServer.Credentials = new NetworkCredential(AuthUser, password);
                SmtpServer.EnableSsl = false;
                SmtpServer.Send(mail);
            }
            catch (Exception exception)
            {
                Exception e = exception;
                status = false;
                LogHandler.getInstance().Log(e);
            }
            return status;
        }

        public static int timeComparison(TimeSpan time1, TimeSpan time2)
        {
            return TimeSpan.Compare(time1, time2);
        }

        public static bool ToBoolean(object str)
        {
            bool flag;
            try
            {
                flag = Convert.ToBoolean(str);
                return flag;
            }
            catch
            {
            }
            flag = false;
            return flag;
        }

        public static DateTime ToDateTime(object str)
        {
            DateTime dateTime = DateTime.MinValue;
            string strDate = str.ToString();
            try
            {
                dateTime = Convert.ToDateTime(strDate);
            }
            catch
            {
            }
            return dateTime;
        }

        public static string ToDBString(object obj)
        {
            return (obj == null || Convert.IsDBNull(obj) || string.IsNullOrEmpty(obj.ToString()) ? "NULL" : obj.ToString());
        }

        public static double ToDouble(object str)
        {
            double num;
            try
            {
                num = Convert.ToDouble(str);
                return num;
            }
            catch
            {
            }
            num = 0;
            return num;
        }

        public static int ToInt(object str)
        {
            int num;
            try
            {
                num = Convert.ToInt32(str);
                return num;
            }
            catch
            {
            }
            num = 0;
            return num;
        }

        public static long ToInt64(object str)
        {
            long num;
            try
            {
                num = Convert.ToInt64(str);
                return num;
            }
            catch
            {
            }
            num = (long)0;
            return num;
        }

        public static string ToString(object obj)
        {
            return (obj == null || Convert.IsDBNull(obj) ? "" : obj.ToString());
        }

        public static bool TryParseDate(object str)
        {
            DateTime dateTime = DateTime.MinValue;
            bool flag = true;
            str.ToString();
            try
            {
                dateTime = Convert.ToDateTime(str);
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        public static bool tryParseInt(object num)
        {
            bool flag = true;
            try
            {
                Convert.ToInt32(num);
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        public static bool TryParseRealNumber(object num)
        {
            bool flag = true;
            try
            {
                Convert.ToDouble(num);
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        public static bool TryParseWholeNumber(object num)
        {
            bool flag1;
            bool flag = true;
            if (!(num as string).Contains("."))
            {
                try
                {
                    Convert.ToInt32(num);
                }
                catch
                {
                    flag = false;
                }
                flag1 = flag;
            }
            else
            {
                flag1 = false;
            }
            return flag1;
        }

        public static void UndoImpersonation()
        {
            PGUtil.impersonationContext.Undo();
        }

        public static string[] YTD()
        {
            string[] dates = new string[2];
            DateTime utcNow = DateTime.UtcNow.AddHours(5.5);
            int year = utcNow.Year;
            DateTime firstDate = new DateTime(Convert.ToInt32(year), 1, 1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            utcNow = DateTime.UtcNow;
            dates[1] = PGUtil.FormatSQLDate(utcNow.AddHours(5.5));
            return dates;
        }
  

     private string GetActiveDirUserDetails(string userid)
    {
 System.DirectoryServices.DirectoryEntry dirEntry = default(System.DirectoryServices.DirectoryEntry);
 System.DirectoryServices.DirectorySearcher dirSearcher = default(System.DirectoryServices.DirectorySearcher);
 string domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
 try {
  dirEntry = new System.DirectoryServices.DirectoryEntry("LDAP://" + domainName);
  dirSearcher = new System.DirectoryServices.DirectorySearcher(dirEntry);
  dirSearcher.Filter = "(samAccountName=" + userid + ")";

  dirSearcher.PropertiesToLoad.Add("GivenName");
  //Users e-mail address
  dirSearcher.PropertiesToLoad.Add("sn");
  //Users last name
  SearchResult sr = dirSearcher.FindOne();
  //return false if user isn't found 
  if (sr == null) {
   return false;
  }
  System.DirectoryServices.DirectoryEntry de = sr.GetDirectoryEntry();
  dynamic userFirstLastName = de.Properties("sn").Value.ToString() + ", " + de.Properties("GivenName").Value.ToString();
  return userFirstLastName;
 // return false if exception occurs 
 } catch (Exception ex) {
  return ex.Message;
 }
    }
 
 }
  
  
  
  
  

Saturday 22 November 2014

STEP BY STEP WEBAPI FOR BEGINEERS

Asp.Net Web API Overview

download code from here:WebApi Example
Note:please change database connection in web.config
Asp.Net Web API is a framework build on .NET for building HTTP services that can be consumed by a wide range of clients including browsers, mobiles, iphone ...... If you know MVC then you can are already know 75%  webApi. It contains the MVC features such as routing, controllers, action results, filter, model binders, IOC container/ dependency injection. Remember,It is a part of the core ASP.NET platform and not MVC and can be used with MVC and Web applications like Asp.Net WebForms.

ASP.NET Web API Features

  1. It supports convention-based CRUD Actions since it works with HTTP verbs GET,POST,PUT and DELETE.
  2. Responses have an Accept header and HTTP status code.
  3. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.
  4. It has default  support for OData. Hence by placing the new [Queryable] attribute on a controller method that returns IQueryable, clients can use the method for OData query composition.
  5. It can be hosted on IIS and in  application also
  6. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection that makes it more simple and robust.
  7. It is only based on HTTP and easy to define, expose and consume in a REST-ful way.
  8. It is light weight architecture and good for devices which have limited bandwidth like smart phones
Point to be Noted:- You can use WebAPI only with HTTP which make it different from WCF ,which supports all protocols
So, we can say that using ASP.NET Web API, we can create HTTP services
  • WebAPI is non-SOAP based like plain XML or JSON string.
  • using full features of HTTP.So, can reach broader range of clients (browsers and mobile devices...).
Following is the typical ASP.NET Web API processing architecture.

What is the difference between Asp.Net Web API and Asp.Net MVC

Asp.Net MVC is used to develop web applications that returns both views and data but Asp.Net Web API is used to create HTTP services with easy way that returns only data not view like in MVC.
Apart,Web API helps to build true REST-FUL services over the .NET Framework and it also support CONTENT NEGOTIATION which mean deciding or choosing the best response format data like (JSON,XML,ATOM or any other formatted data) that could be acceptable by the client.


CREATE ASP.NET WEBAPI

  • Open Visual Studio/Visual Express and create “New Project” i.e. File -> New Project.
  • Choose “ASP.NET MVC 4 Web Application” template and name project as “WebAPIExample”.
  • When you click “OK” button, a new window will appear for selecting a sub-template. Actually for ASP.NET MVC 4 Web Application, we have multiple sub-options i.e. Empty, Internet Application, Web API etc.
  • Choose “Web API” and simply press “OK” button.

CREATE REAL TIME WEBAPI :

Let us modify existing service and create webapi service to perform CRUD operation on User:-
we need to prepare the model.
  • Right click on the “Model” folder and fallow below steps
7

We are done with domain creation.
CREATE CONTROLLER
Controller class plays an important role, because request coming from client hits the controller first. Then the controller decides which model to use to serve the incoming request. So, in order to add a controller:
  • Right click on the “Controller” folder and choose “Controller” under “Add” from the context menu as shown in figure.
  • Name the controller as “UserController”.

So you have created Controller which looks like shown above.
Before you continue,Just think what all Actions/Methods you need .I will assume that we need to create WebAPI Service Which will
  • Get All Users

  • Get User based on Id

  • Insert User

  • Delete User

 Let We first Create Data Access related Class for above functionality

Considering you as begineers in WebApi ,please fallow  below steps
  1.  Go to Model folder and add folder with "DAL" name.
  2. Right Click on folder and add class with name UserRepository as show below
     public class UserRepository
        {
            p10Entities p10entities;
            public List DbGetAllUsers()
            {
                p10entities = new p10Entities();
    
                return p10entities.users.ToList();
    
            }
            public User DBGetUser(string username)
            {
                User user = p10entities.users.SingleOrDefault(u => u.UserName == username);
                return user;
            }
    
            public string DBRegisterUser(User user)
            {
                p10entities.users.Add(user);
                int recSaved = p10entities.SaveChanges();
                if (recSaved == 1)
                    return "Saved";
                else
                    return "Failed";
    
            }
            public void RemoveUser(int id)
            {
             // code for deletion
            }
    
            public bool UpdateUser(User userrname)
            {
               //code for updation
                return true;
            }
        }
    
    

    So,in above code youy will see " p10Entities". what is it ? DbContext :Simplfied alternative to ObjectContext and is the primary object for interacting with a database using a specific model. So,we are done with dataAccess related functionality,now we have to expose it to external world in the form of JSON or XML
  3. Go to Controller which we created at the begining and add below code
     public class UserController : ApiController
        {
            UserRepository userRepository;
            public HttpResponseMessage GetAllUsers()
            {
               userRepository = new UserRepository();
               var users=userRepository.DbGetAllUsers();
               var resp = new HttpResponseMessage(HttpStatusCode.OK);
               resp.Content = new ObjectContent>(
                users, new JsonMediaTypeFormatter());
               resp.Headers.ConnectionClose = true;
               resp.Headers.CacheControl = new CacheControlHeaderValue();
               resp.Headers.CacheControl.Public = true;
               return resp;
            }
            public HttpResponseMessage UserByUserName(string username)
            {
                userRepository = new UserRepository();
                var users = userRepository.DbGetUser(username);
                var resp = new HttpResponseMessage(HttpStatusCode.OK);
                resp.Content = new ObjectContent(
                                        users, new JsonMediaTypeFormatter());
                resp.Headers.ConnectionClose = true;
                resp.Headers.CacheControl = new CacheControlHeaderValue();
                resp.Headers.CacheControl.Public = true;
                return resp;
            }       
            public string AddUser(User user)
            {
                userRepository = new UserRepository();
                userRepository.DbAddUser(user);
                return "Added";
            }
            public string Delete(string id)
            {
                userRepository = new UserRepository();
                userRepository.DbRemoveUser(id);
                return "Deleted";
            }
        }
    
  4. Finally, just build your solution and try to put API's in action like shown below.

Next we will see how to clean up code and use DEPENDENCY INJECTION AND UNIT OF WORK Patterns..

Sunday 19 October 2014

Simple and Clear Explaination of Sharepoint for All


Sharepoint History

I am sure most of the people will be still wondering about  “What SharePoint is?” and "Why and Who needs Sharepoint?"  . Before we will understand starepoint, I just  want to give you brief about history of sharepoint
sharepoint history
 To conclude from above history , sharepoint2007 was the first successful release which was accepted on enterprise level as content management system


What is sharepoint ?

SharePoint is Sharepoint is not only Content Management system.but it actually offers much more .... It could be described as an enterprise collaboration platform with a huge capabilities like it can be used as:
  • Application platform that you can transform into a tailor -made content management solution with a bit customization and development
  • Complete Document management system with simple configuration
  • Record Management system
  • Digital Asset Management system(DAM) in the form of SharePoint Libraries are where documents and other types of files (pictures, music files, videos, etc.)
  • Builder for Website,Wiki Blog and other types of teamsite  with two or three steps along with user management authentication and authorization
  • Application ,Website deployer
  • Alert and Notification System.
  • Workflow based system platform
So, We can say SharePoint is a platform which provides great number of tools with various functionalities required for businesses .Since it isn’t one tool, and because you can create highly customized solutions with it, the best way to describe it is to explain some of the things businesses use it for.
  • Intranet An intranet is an internally facing website where people in your company sign in to find news, announcements, scheduled tasks, and access to a variety of information.
  • Extranet SharePoint can also be used to set up an extra-net, a portion of your site that you share with outside businesses/partners you’re partnering with.  . 
  • Document Storing and Sharing SharePoint gives businesses a shared space to store documents so they’re not locked away on any one person’s hard drive. Documents stored on SharePoint can be accessed by anyone in the company - unless the administrator has limited access to a smaller group.
  • Web Content Management You can use SharePoint to build and manage a publicly facing website as well. As a Web Content Management System (WCMS), SharePoint allows you to sign in and make changes to your pages. You can update information, add text or graphics, and create new pages.
  • Collaboration It’s easy for everyone to stay up-to-date and coordinate their efforts on projects when you’re talking about a dozen or so people working out of the same office building. SharePoint is designed to extend this ease of interaction beyond small groups in single locations. You can sign in to SharePoint from any desktop or mobile device, and you can use it to have constant access to information on project statuses, client histories, the location, availability, and schedule of coworkers, and anything else related to the project.
  • Business Intelligence The comprehensive access SharePoint provides to your business’s data also makes it possible to find countless ways to use all that information to make better decisions. SharePoint makes it easy to search through all your company’s files, but beyond that it can help you discover larger patterns .



AS A DEVELOPER YOU CAN DEFINE :

Before i will define it , i wish to ask developer a simple question like
Q: How long it will take you to develop a site/solution in .net ?
Obviously , more precise or further clarification from developer will be  ,  whether using ASP.NET Webform or MVC ? why ? because every developer know that using asp.net webfarm it will take less than MVC because ASP.NET has all ready made rich controls available for building sites/solutions in hours.Well , i assure you same site/solution can be developed in sharepoint just in minutes because sharepoint is richest
sharepoint as a platform with a rich frame- work for developing business related applications/solutions rapidly. SharePoint is simply a rich set of tools, classes, libraries, controls, and so on, that are useful for building business solutions focused on collaboration, content management, social networking, content searches, and more more.... Many people think of SharePoint as a platform that’s ready to use for building websites—usually for intranet or extranet scenarios. That’s true, but is partially true ! Certainly, SharePoint is a platform for building websites, and of course, it can target intranet and extra-net sites. But it is much more, as well; you can use it to build any kind of web solution, including Internet publishing sites, by taking advantage of its well-defined and ready-to-use set of tools, based on a secure, scalable, and maintainable architecture.
You can think of SharePoint as a super-set of Microsoft ASP.NET, with a broad set of services that can speed up the development of web-based collaborative solutions. You should use SharePoint as a shared connection point between users, customers, and whoever else uses your websites and the applications they utilize. The fundamental idea of SharePoint is to share con-tent, applications, and data to improve collaboration and provide a unique user experience. SharePoint itself is primarily a container of content and apps. Content is organized in lists, and each list is made up of items. A list can consist of simple items with custom metadata properties called fields. Lists can also be libraries of documents, which are a particular kind of item that correspond to document files. Almost always when you develop a SharePoint solution, you manage lists and items.

Which software do I need?

  • SharePoint Foundation    The underlying technology for all SharePoint sites. SharePoint Foundation is available for free on premises deployment—in previous versions it was called Windows SharePoint Services. You can use SharePoint Foundation to quickly create many types of sites where you can collaborate on Web pages, documents, lists, calendars, and data. Download SharePoint Foundation 2013.
  • SharePoint Server    Organizations can deploy and manage SharePoint Server on premises. It includes all the features of SharePoint Foundation plus additional features and capabilities, such as Enterprise Content Management, business intelligence, enterprise search, personal sites, and Newsfeed. Give SharePoint Server 2013 a try!
For more information about trying, buying, or using SharePoint products and technologies, see SharePoint product information.
If you’re familiar with SharePoint and you’re looking to see what’s changed in the latest release, see What’s new in Microsoft SharePoint Online and What’s new in Microsoft SharePoint Server 2013.

Core features of SharePoint?

Every new version of sharepoint brings ,new and exciting tools . but core of the tools that makes SharePoint an exceptional platform for Content management, Business Process Management, Collaboration and Web Publishing are:
  • SharePoint Sites facilitates to create websites.
  • SharePoint Communities plays it’s role to collaborate with other peoples.
  • Contents makes SharePoint a true CMS (Content Management System)
  • Search Engine provides smart and efficient searching of enterprise contents.
  • Insights brings information together from different data sources.
  • Composition makes SharePoint an extensible platform and extends it’s capabilities by using different tools like SharePoint Designer etc.

SharePoint 2013 New Features?

New features are released with every version of SharePoint. SharePoint 2013 also packaged with lots of new features. Few of them are listed here:
  • Cross-Site Publishing
  • Improved Performance
  • Design Manager for Publishing Sites
  • Improved and better Search
  • Changes in SharePoint Workflow Architecture
  • Office Web Apps Server
  • Improved Social Computing Features
  • Optimized User Interface for Mobile Devices
  • Shredded BLOBs for Storage
  • New Features to BCS (Business Connectivity Services)

Checking Out Microsoft SharePoint Features

Ask ten different people to define SharePoint and you’re likely to receive ten different answers, because the Microsoft Office SharePoint product comprises many different technologies.
The following list can help pinpoint each SharePoint component, where you find it, and its purpose:
  • SharePoint Foundation: SharePoint Foundation is a communication, collaboration, and content-management platform that comes free with the Windows Server operating system.
  • SharePoint Server: SharePoint Server is a software product in its own right that expands the basic communication, collaboration, and content-management capabilities of SharePoint Foundation. SharePoint Server comes in four editions:
    • SharePoint Server for Intranet Standard Edition
    • SharePoint Server for Intranet Enterprise Edition
    • SharePoint Server for Internet Standard Edition
    • SharePoint Server for Internet Enterprise Edition
  • InfoPath Forms Services: This SharePoint feature enables you to embed InfoPath forms in SharePoint Web sites.
  • Excel Services: This feature enables you to embed Excel documents in a SharePoint Web site.
  • SQL Server Reporting Services (SSRS) Integration: SSRS Integration is an installation option that coordinates the operation of an SSRS server with a SharePoint environment. SSRS reports are contained and managed in SharePoint instead of being sent to a standalone report server.
  • PerformancePoint Services: With this SharePoint feature, you can develop sites for dashboards and content, including the KPIs (Key Performance Indicators) and Scorecards used in business intelligence.
  • Business Connectivity Services (BCS): A feature of SharePoint that you can use to connect SharePoint to (and integrate it with) your Line of Business (LOB) systems. Using this feature, you can view and edit the data from your business systems within the SharePoint site. Result: You can use the company portal to make use of the backend system.
  • Sites: A SharePoint Site is nothing more than a Web site with the special capabilities that SharePoint provides, in particular Web-site management and easy integration into other SharePoint Web sites.
  • Document Libraries: A Document Library is a mechanism for storing and managing content within SharePoint, using features such as check-in, check-out, versioning, security, and workflow.
  • Lists: A SharePoint List is simply a list of data arranged in columns and rows, used as the basic way to store SharePoint content.
  • Wikis: A wiki is a specialized Web site that allows community members to update the content of the Web site on the fly. Although wikis are not specific to SharePoint, SharePoint does offer Wiki functionality as a feature.
  • Blog: A Web log or online journal. In SharePoint, a blog provides a forum for people to exchange communications that can be viewed across the entire organization or Internet. After a blog entry is posted, the content can be augmented with comments and discussions on the blog-entry page. You can get a SharePoint blog up and running in a manner of minutes.
  • Discussion Boards: A familiar method of online discussion, which SharePoint makes usable throughout the organization. People can post questions and replies to be viewed throughout the organization.


AS A USER

The vastness of SharePoint creates areas of specialization. The result is that a person’s view of SharePoint is greatly affected by how that person uses the product like explained in below picture:


It’s important to keep this in mind when talking with people about SharePoint. If you ask ten sharepoint users to define SharePoint, you’re likely to get ten different answers .SharePoint is a platform, so the user roles an organization defines depend on the organization itself. Here are some examples of the possible roles of users in SharePoint:
  • Anonymous visitor: A person that browses to a Sharepoint website that just happens to be using the SharePoint platform. An anonymous visitor just sees SharePoint as a website and nothing else
  • SharePoint visitor: A person that browses to the site and authenticates so that SharePoint knows who they are. The visitor might still just see a SharePoint site as any other website, except he notices his name in the top-right corner of the screen and knows he must log in to reach the site Visitors might not use any of the features of SharePoint, however, and just browse the information posted to the website
  • SharePoint casual user: A person that knows all the company documents are posted to SharePoint and knows she can upload her own documents to her personal SharePoint site. A casual user might realize that she is using SharePoint, or she might just think of the platform as the name the organization has given to SharePoint For example, some organizations give their web platform tool names such as Source or Smart or Knowledge Center. SharePoint is the name of the web platform product from Microsoft, which is often unknown by users of a tool built on the SharePoint platform
  • SharePoint user: A person that is familiar with SharePoint and its main features. A SharePoint user often performs various administrator functions even if he doesn’t realize it. For example, he might be responsible for an app that stores all the company policies and procedures. He is thus an app administrator A user might also be responsible for a site for a small team, in which case he is a site administrator. As you can see, a user can play many different roles
  • SharePoint power user: A power user is not only familiar with the main SharePoint features and functionality but also dives deeper. A power user might be familiar with the functionality differences of different features, routing documents using workflows, and building site hierarchies. A power user might also be a site collection administrator and thus is responsible for a collection of sites
  • SharePoint technical administrator: A technical administrator is someone from the IT department who is responsible for SharePoint. A technical administrator is less concerned with using SharePoint for business and more concerned about making sure the platform is available and responsive An administrator might play many different roles. For example, farm administrators are responsible for all the servers that make up SharePoint, such as web front end servers, applications servers, and database servers. Specialized database administrators focus just on the database components. There are even administrative roles for specific services, such as the search service or user profile service Depending on the size of the SharePoint implementation, these technical administrator roles might be filled by a single overworked individual or a team with highly specialized skills AS A ADMINISTRATOR:

What All Sharepoint Server Includes

SharePoint 2013 is a huge product. Not only is SharePoint itself complicated but it also relies on a whole series of other technologies to make the magic happen.
The SharePoint 2013 technology stack consists of
  • Computer servers: At the root of any software system is a physical device called a server. A server is no different than your laptop, desktop, or even phone. They all use physical computer chips to make things happen in the digital world. A SharePoint server is just designed specifically for heavy-duty enterprise-type software.
  • Operating systems: A physical computer isn't much more than a paperweight without software to make it function. The software designed to make computers do stuff is called an operating system. In the Microsoft world, the operating system designed for servers is called, aptly enough, Windows Server.
  • Databases: A database is installed onto the operating system and is specifically designed and optimized to store and manipulate data. The Microsoft database product is called SQL Server. SharePoint takes advantage of the advanced capabilities of SQL Server to provide the features users need.
  • Web servers: SharePoint is software that you interact with using your web browser. A special software product called a web server is the engine that delivers web pages to your web browser. The Microsoft web server is called Internet Information Services (IIS).
You have a few different options when choosing SharePoint 2013:
  • SharePoint Foundation 2013: Basic collaboration using team sites, blogs, and apps
  • SharePoint Server 2013, Standard license: Intranet, portals, extranets, search, and My Site social network
  • SharePoint Server 2013, Enterprise license: Advanced scenarios for business intelligence, application integration, and Office 2013 services
  • SharePoint Online: The cloud-based version of SharePoint 2013, offered as a standalone product or bundled with Office 365, includes a number of different package options that are a mix of the SharePoint Foundation and SharePoint Server features

Working with the Office 365 Suite of Products

The Office 365 product is actually an umbrella term that encompasses four different technologies that have been woven together to provide a seamless solution in the cloud. Use this reference to quickly get a handle on Office 365 and its components as well as their purpose and problems they are designed to solve.
Component Description
SharePoint Online SharePoint is Microsoft’s web platform and is designed to provide communication, consolidation, collaboration, and content management.
Exchange Online Exchange is Microsoft’s email server designed to handle the heavy lifting of managing and routing emails. In addition Exchange handles functionality such as contacts, calendars, and tasks. Users generally use an email client such as Outlook to connect to Exchange.
Lync Online Lync provide instant communication and ad-hoc meetings. Lync lets you conduct online meetings by sharing your screen or presentations online with multiple users simultaneously while communicating via voice, chat, and surveys. Lync is integrated with the other products in Office 365 in order to provide instant ability to communicate regardless of what software you are using.
Office Professional Plus Office Professional Plus is the nearly ubiquitous productivity suite used by information workers around the world.

Understanding Key Components of SharePoint Online

SharePoint contains a huge amount of functionality. Use below terms and acronyms as reference to quickly understand the components of SharePoint.
Component Description
Site Collection A SharePoint Site Collection is a top level site that contains other sub-sites. The difference between a Site Collection and a Site is that a Site Collection contains separate security and is isolated from other Site Collections. A Site on the other hand is contained by a top level Site Collection and shares security and other aspects with other Sites within the same Site Collection.
Sites A SharePoint Site is nothing more than a website. At its root SharePoint is a website management system that provides a rich assortment of functionality that can be easily integrated into the SharePoint websites.
Document Libraries A Document Library is a mechanism to store content within SharePoint. A Document Library provides functionality for content management such as check-in and check-out, versioning, security, and workflow.
Lists A SharePoint List is simply a list of data. Much like you would have a grocery list a SharePoint List stores data in columns and rows.
Wikis A Wiki is a specialized website that allows community members the ability to update the content of the web site on the fly. A Wiki is not specific to SharePoint however SharePoint provides Wiki functionality as a feature.
Blogs A Blog is a web log or online journal. A blog provides a forum for people to write communications that can be viewed across the entire organization or Internet. Once a blog entry is posted the content can be commented and discussed on the blog entry page. Blogs are prevalent throughout modern society and SharePoint provides the ability to get a blog up and running in a manner of minutes.
Discussion Boards A Discussion Board allows for online discussion throughout the organization. A discussion board provides a forum for people to post questions and replies that can be viewed throughout the organization.

Understanding Key Components of Exchange Online

Exchange is often thought of as only being an e-mail server. The Exchange product contains a number of additional components, such as calendars, contacts, and tasks. Use this reference to quickly understand the different aspects of Exchange.
Component Description
Mail E-mail is probably the most used for of communication in the modern age. Exchange excels at handling e-mail. You connect to Exchange using an e-mail client such as Outlook.
Calendar If you use Outlook then you are familiar with booking your meetings and appointments on the Calendar tab. Exchange is the actual product that handles these events because Outlook is just the client.
Contacts Having a place to store all of your contacts is critical in today’s connected world. With Exchange all of your contacts are stored on the server and can be accessed to by any connected device. For example, you can use your mobile phone, laptop, home computer, or work computer. You can even connect by using any computer that has a web browser through Outlook Web Access (OWA).
Tasks Unless you have the memory of a savant then you probably work from a task list. When you store your tasks in Outlook you are actually storing them out in the cloud in Exchange. Just like the other aspects of Exchange, your tasks are available from any connected device. Because your tasks are in Exchange, you can add a task on your laptop and have it instantly available on your work computer when you login.

Understanding Key Components of Lync Online

You can use Lync to communicate in a number of different ways. Lync lets you do everything from sending an e-mail with a click of the mouse to conducting an instant and ad-hoc meeting with people around the world. Use this reference to gain an understanding of the components of Lync.
Component Description
Meetings Lync allows you to conduct instant and ad-hoc meetings. Using Lync you can share your computer screen or applications so that everyone in the meeting is looking at the same thing. You can use features, such as a virtual white board, shared chat rooms, questions, and surveys.
Lync meeting functionality is integrated tightly with Outlook so that you can create meetings and invite participants on the fly with only a few clicks of the mouse.
Messaging Lync allows you to send messages by using popular messaging platforms, such as Yahoo, AOL, Windows Live in addition to internal corporate users.
Voice Lync integrates with your corporate phone system to provide one-click calling as well as other features, such as having voicemails sent to your e-mail and Outlook.
Video Using Lync you can integrate video into meetings and messaging for as close to an in person experience as possible.


Who needs it?

Obviousely every organisation who are:-
  • designed to enable people to work together on the same project, keep files up to date, input into documents and make working together simpler and easier. Microsoft SharePoint can make it easier for your organization to work together, collaborate on ideas and quickly respond to changing business needs
  • want to expose business intelligence and big data reports Integration between SharePoint and Excel is even tighter, too.
  • People that work with information spend at least one third of their time looking for information. Improving the efficiency of that process and improving its quality provide major
    benefits for a business. SharePoint combined with Search Server Express provide an excellent way to index most business information quickly and efficiently. Helping a business find their
    information quickly will ensure the success of any SharePoint project.

Common SharePoint 2013 Site Templates

A site template is what you use when you create a new SharePoint site. It provides you with a starting setup for SharePoint. A number of site templates are available in SharePoint 2013. Site templates are grouped into categories such as Collaboration, Enterprise, and Publishing.
Note: Which site templates are available to you depends on which SharePoint 2013 edition you're using, as well as the features that are activated. For example, the Business Intelligence Center template is available only with the Enterprise license.
The site templates you should be familiar with include
  • Team Site: Enables teams to collaborate, share documents, and stay in sync.
  • Blog: Produces a blog site.
  • Project Site: Enables teams to manage and collaborate on a specific project.
  • Community Site: Allows community members to congregate and discuss common interests.
  • Document Center: Enables managing common documents in a central location.
  • Records Center: Manages company records.
  • Business Intelligence Center: Provides all the functionality required for business intelligence in SharePoint.
  • Enterprise Search Center: Enables search and includes a number of search results pages for specialized queries, such as searching for people, conversations, videos, and general.
  • Basic Search Center: Provides a general search center site. The basic lacks the multiple results pages of the enterprise class search center.
  • Visio Process Repository: Stores business processes in Microsoft Office Visio format.
  • Publishing Site: Creates a blank publishing site. A publishing site is used to publish web pages for mass consumption.
  • Publishing Site with Workflow: Provides the capabilities of the Publishing Site template and also includes approval workflows.
  • Enterprise Wiki: Captures and stores information from a group collective.

SharePoint’s Site Hierarchy Model

All of Microsoft SharePoint’s features are delivered via a hierarchy of Web sites. This sample SharePoint hierarchy begins at folders and moves up the chain to the server farm.
image0.jpg

Difference Between Web Applications Vs Site Collections Vs Sites in SharePoint.

SharePoint Site is just a website. SharePoint allows us to create varieties of websites for specific purpose like Personal site, a Team Site, a social media site, a blogs or a Wiki Site etc.
While Site Collection is a collection of SharePoint sites that share common features like Content types, Templates, Site columns, permissions, Web Parts etc.
A Web Application is a collection of Site Collections in SharePoint OR in order way a site collection resides in a web application.This is root/parent for all site and site collections

Site Templates in SharePoint 

SharePoint provides loads of templates you can use for creating sites. By far the two most popular are the team site and publishing sites. But SharePoint offers a lot more choices beyond those two. What’s more, your company can even create site templates that are specific to your company.
The term site template is overloaded. Technically, the site templates provided by Microsoft are site definitions, which is just an XML file that describes how to create a site. Site definitions reside on the file system. The site templates that you create from your sites are just Microsoft cabinet files that contain the objects required to stamp out a new site.
Site templates are stored in the site collection and can be shared easily with other people. A site template is tied to one of the underlying Microsoft site definitions. A site template creates a new site using the Microsoft site definition and then builds out the site using the objects contained in the cabinet file.
SharePoint provides dozens of site templates that fall into a handful of categories. Within each category, the templates are basically the same only with slight variations. Each category is optimized to serve a different audience or function.
Team sites are almost always the de facto standard for collaboration sites used for project teams. Publishing sites are usually used for public-facing websites.
The following table outlines the site template categories, lists the templates you can except to see, and when you should use them.
SharePoint Site Template Categories
Category Templates You See When to Use Them
Blank & Custom Blank Site When you want an empty container
Collaboration Team Site and Meeting Workspaces When more people will contribute content than read it; also when you want basic layouts
Content & Data Blog, Contacts Web Database, Personalization Site, Document Center, Publishing Site, Enterprise Wiki, Visio Process Repository When you need a site that specializes in content or data management
Search Basic Search Center, Enterprise Search Center When you need a site to display search results
Tracking and Web Databases Assets Web Database, Charitable Contributes Web, Projects Web Database When you want to use a Web-based database to create track of information
If you’re creating new site collections, you see a slightly different set of categories along with a few additional templates. Also, the templates you have available to you are dependent on how your company has licensed SharePoint and what features they have turned on.
In a publishing site, you can control which templates can be used to create site templates. On the Site Settings page, click the Page Layouts and Site Templates link.

Introduction to site collections and site collection administrators

If you work on a site, you are working inside a site collection. Every site exists within a site collection, which is simply a group of sites and content that are located under a single top-level site.
Here is an illustration of a site collection, along with the types of sites and content that a site collection might contain.
Description: Visualize the scope of permissions
A site collection administrator determines initial permissions settings for the whole site collection. All the sub-sites and content in a collection inherit the permissions settings that the site collection administrator chooses for the top-level site.
If you are a site collection administrator, this means the following:
  • You should work closely with the people who create your site collection.
  • You are responsible for deciding who has access to important intellectual property stored on your organization’s sites (that is, for setting site-collection level permissions).
If you are a site owner, or are responsible for restricting access to a specific item of content, you can work with the permissions settings for your sites to customize the permissions settings for your area.

1.3 Visualize the components of permissions

At the most basic level, you manage permissions settings by granting or restricting user access. This is true for many different roles, whether you are a site collection administrator, a site owner, or just someone who works with a single document. To grant user access, you work with three interrelated features:
  • Security groups
  • Permissions levels
  • Permissions inheritance

Description: Visualize the components of permissions
The best place to start is with security groups. In most circumstances, you can do everything you need to do about controlling access simply by working with security groups. Permission levels and permission inheritance run smoothly behind the scenes.

1.4 Security groups

A security group is a collection of people—known as users—who all need to perform similar types of tasks on your site. For example, some people might only need to see information on your site, while another group might need to edit it, as well.
Groups give you the power to control access to sites for many people at once.

1.5 Permission levels

Security groups are assigned permission levels. Permissions levels are combinations of tasks that people need to be able to perform on your site, such as “view pages on the site,” and “view items in a list”; or, “create a list,” or “add an item to a list.”
By grouping commonly associated tasks into permission levels, you can grant security groups permissions to perform many tasks on a site or content item at once.

1.6 Permissions inheritance

By default, sites and content inherit groups and permission levels from the site above them in the site hierarchy—from their parent site. Permissions inheritance gives you the power to manage all your permissions for a site and all its sub-sites and all the content on it and its sub-sites, from one place—the top site—quickly and efficiently.

1.7 Restrict access to one specific piece of content

In some cases, your site might contain content that only certain people or groups may access. For example, if you have a list on your site that contains sensitive data, you might want to restrict who can see it. To do this, you break permissions inheritance, and then edit permissions for the content on its own permissions page.

2. How to create new site collection?

To create new site collection, you must be one of a tenant administrator.
  1. Go to the tenant administration site using your FAITH-COM\UID and PIN.
    https://<dept-domain-name>.workspace.faith.share/sites/clientadmin/
     
  2. Under SharePoint Sites, click Manage Site Collections
  3. Click New Icon Image icon at the top.
  4. Input the following information, and then click OK.
    Create New Site Collection Image
    • Title and Description
    • Web Site Address
    • Template Selection
    • Primary Site Collection Administrator
  5. The newly created site collection will be on the list, click the Manage Icon ImageManage icon.
Manage Site Collection Image
  1. In the Site Settings page, under Site Actions, click Manage site features.

    Manage Site Features Image
  2. Click the Activate button of the Content Organizer features

    Content Organizer Image
  3. Now, three default user groups are created below, site collection administrator can make use of these to manage the user access control.
    • <site-collection> Owners
    • <site-collection> Members
    • <site-collection> Visitors

3. How to change locale in site collections?

To change locale in site collections, you must have at least the permissions obtained by being added to the default <Site Name> Members group for the site.
  1. Go to the site which you want to change the locale.
    https://<dept-domain-name>.workspace.faith.share/sites/<your-site>/ [3]
     
  2. Click Site Setting Image 1  Site Setting Image 2
  3. Under Site Administration, click Regional settings

    Regional Setting Image
  4. Change the Locale and then click OK.

Locale Setting

4. How to set/check site collection disk quota?

To set disk quota on site collection, you must be one of a tenant administrator.
  1. Go to the tenant administration site.
    https://<dept-domain-name>.workspace.faith.share/sites/clientadmin/
     
  2. Under SharePoint Sites, click Manage Site Collections
    Manage Site Collections Image
  3. Select the site collection which you want to set the disk quota by check the box on the left hand side of the site collection URL. (Do not click the URL itself)
    Check Disk Quota Image
  4. Click Disk Quota Icon icon at the top.
     
  5. You can check the current storage used by this site collection.
     
  6. Update the limits according to your need, and then click OK.
Check Current Storage Image

5. How to check and update site collection administrators?

Site Collection Administrators are given full control over all Web sites in the site collection. To check and update site collection administrators, you must be one of a site collection administrator.
  1. Go to the site which you want to check or update site collection administrators.
    https://<dept-domain-name>.workspace.faith.share/sites/<your-site>/
  2. Click Site Settings Image >Site Collection Administrators Image
  3. Under Users and Permissions, click Site collection administrators
    Site Collection Administrators Image
  4. Update the site collection administrators list, and then click OK.

Site Collection Administrators List Image

6. Edit permissions for a list, library, or individual item

This topic explains how to assign unique permissions for an individual site, list, library, folder, list item, or document.

6.1 Introduction to setting individual permissions

In some cases, your site might contain content that’s only meant for certain users or groups. For example, if you have a list on your site that contains sensitive data, you might want to restrict who can see it.
To do this, you break permissions inheritance, and then edit permissions for the content on its own permissions page.
Restricting access to content follows these same basic steps:
  1. Open the permissions page for the piece of content you want to restrict access to, and break inheritance from its parent.
     
  2. Remove groups or users that you don’t want to have access to the content.
     
  3. Grant permissions to new groups or individuals that you do want to have access.
You can resume inheriting permissions from a parent list, the site as a whole, or a parent site at any time. (Note that if you do so, you’ll lose any unique permissions that were applied directly to the content.

6.2 Example: Restrict access to a list

Here’s an example in which you restrict access to a list. You can follow the same steps for a site, library, or individual item, working from the permissions page for that item.

6.3 Break inheritance from the parent.

  1. Open the list that you want to restrict access to.
     
  2. On the List Tools tab, click List to open the gallery of commands specific to the list.
    List Tools Image
  3. On the ribbon, click the List Permissions buttonList Permissions Button Image.
    List Permissions Image
    The permissions page for the list opens, with a yellow status bar that explains that the list inherits permission from its parent site.
Inherits Permission Image
  1. Click the Stop Inheriting Permissions button
    Stop Inheriting Permissions Image
    Now the list is disconnected from the parent site.
    Disconnected Inheriting List Image
    Here are two important things to note:
  • The list still has the same permission settings that it did before. But now, instead of inheriting permissions from the parent, it has its own copy of the parent’s permissions.
     
  • Changes that you make to the permissions settings for the parent site will not be inherited by this list.

6.4 Remove groups or users you don’t want

  1. In the Name section of the permissions page, select the checkboxes for the groups or users who should not have access to this list.
    Select Group Image
  2. Click Remove User Permissions Remove User Permissions Button Image.
    The permissions page updates to show that the group or user no longer has permissions to the list.
    Permission List Updated Image

6.5 Grant access to groups or individuals

  1. On the permissions page for the list, on the Edit tab, click the Grant Permissions button Grant Permissions Button Image.
    Grant Permissions Image
  2. Type the name of the group or the individual you want to grant access to in the Users/Groups box.
     
  3. Choose the level of permissions you want the group or individuals to have.
     
  4. Click OK.
Choose Permission Level Image

6.6 Reconfigure a list to inherit permissions

After you’ve broken permissions inheritance between a site, folder, list, library, list item, or document and its parent, you can restore inheritance at any time.
  1. Open the list that you want to restore inheritance for.
     
  2. On the List Tools tab, click List to open the gallery of commands specific to the list.
    List Tools Image
  3. On the ribbon, click the List Permissions buttonList Permissions Button Image.
    List Permission Buttons Image
  4. On the list permission page, click Inherit Permissions Inherit Permissions Button Image.
    Inherit Permission Image

7. Check permissions for a person or site

You can find out quickly and easily who has access to what on your sites and content, and you can easily determine whether a site, list, or library contains content with unique permissions.

7.1 Check the permissions for a site

  1. ClickSite Collection Button, and then clickSite Permissions.
     
  2. The permissions page displays all the users and security groups with access to the site, along with the permission levels assigned to them.
    Check Site Collection Image

7.2 Check the permissions for an individual or a security group

  1. ClickSite Actions Button, and then clickSite Permissions.
     
  2. Under Users and Permissions, click Site permissions
    Site Permissions Image
  3. On the Permission Tools tab, click Check Permissions.
    Check Permissions Image
  4. Type the UID of the person or group you want to check, and then click Check Now.
    Check User Group Image
    The Check Permissions dialog box displays name of the person or group you checked, along with the permission levels assigned to them and where the permission levels come from: That is, whether the person has permissions through membership in a group, or as an individual.

8. How to check site quota and usage?

You can check site quota, usage and activities from the Web Analytics Report Summary with the URL below.
https://<dept-domain-name>.workspace.faith.share/sites/<site-name>/_layouts/usage.aspx
Example: https://itservices.workspace.faith.share/sites/testsite/_layouts/usage.aspx [6]
Note: You must have at least the permissions obtained by being added to the default <Site Name> Members group for the site.
Web Analytics Report Image

9. How to check the Site Web Analytics Reports?

To check the site Web Analytics Report, you must have at least the permissions obtained by being added to the default <Site Name> Members group for the site.
  1. Go to the site which you want to check the Site Web Analytics Reports.
    https://<dept-domain-name>.workspace.faith.share/sites/<Your-site>/
     
  2. Click Site Actions Image > Site Setting Image
     
  3. Under Site Actions, click Site Web Analytics reports
Site Web Analytics Reports Image 1
Site Web Analytics Reports Image 2

10. Configure the Quick Launch for site navigation

To configure the quick launch for site navigation, you must have at least the permissions obtained by being added to the default <Site Name> Members group for the site.
Quick Launch Image 1
  1. Go to the site which you want to change the locale.
    https://<dept-domain-name>.workspace.faith.share/sites/<your-site>/
     
  2. Click Site Actions Image 1 > Site Actions Image 2
     
  3. Click Quick launch
    Quick Launch Image 2
  4. Do any one of the following:
    Quick Launch Image 3
    • ClickNew Navigation Link Button, and then input the required information.
      New Navigation Link Image 1
    • ClickNew Heading Button, and then input the required information.
      New Navigation Link Image 2
    • ClickChange Order Button, and then change the order.
      New Navigation Link Image 3
    • ClickEdit Navigation Links Image to edit the Navigation links or Headings.

11. Configure the top link bar for site navigation

To configure the top link for site navigation, you must have at least the permissions obtained by being added to the default <Site Name> Members group for the site.
Top Link Bar Image 1
  1. Go to the site which you want to change the locale.
    https://<dept-domain-name>.workspace.faith.share/sites/<your-site>/
     
  2. ClickSite Action Image > Site Settings Image
     
  3. In the Look and Feel column, click Top link bar.
    Top Link Bar Image 2
  4. Do one of the following:
    1. To add a new link, click New Navigation Link Button. Type the URL and a description for the link. The URL can link to any valid path, such as a folder within this site, a share within your organization’s intranet, or a link to a location on the internet.
      Config Top Link Bar Image 1
      Config Top Link Bar Image 2
    2. To edit a link, click the Edit button beside the link that you want to edit Description: Editand make any necessary changes. You can only edit the description for the default links, such as Home.
       
    3. To remove a link, click the Edit button beside the link Description: Edit, click Delete, and then click OK.
      Important: When you delete a heading from the top link bar on a non-publishing site, any links contained under that heading are also deleted.
       
    4. Click OK.

12. How to assign more staff as tenant administrators?

To assign more staff as tenant administrators, you must be one of a tenant administrator.
  1. Go to the tenant administration site.
    https://<dept-domain-name>.workspace.faith.share/sites/clientadmin/
     
  2. Click Site Actions Button Image, then Site Permissions Button Image
     
  3. Click Site Collection Administrators
    Site Collection Administrators Image
  4. Input the UID of the staff, and then click OK.
    Site Collection Administrators Window

    There's lots of  SHAREPOINT good books
    • Discover SharePoint (PDF)
    • Deployment guide for SharePoint 2013 (DOC PDF EPUB MOBI)
    • SharePoint Adoption Guide (PDF)
    • Explore SharePoint 2013 (DOC PDF EPUB MOBI)
    • The Wiki Ninjas Guide to SharePoint 2013 (PDF)
    • The Wiki Ninjas Guide to SharePoint 2013 – Part II (PDF)
    • SharePoint 2013: SharePoint Customer Audit Process (PDF)
    • SharePoint Products Keyboard Shortcuts (PDF)
    • Business continuity management for SharePoint Server 2010 (PDF EPUB MOBI)
    • Deployment guide for SharePoint Server 2010 (PDF EPUB MOBI)
    • Get started with SharePoint Server 2010 (PDF EPUB MOBI)
    • Explore SharePoint 2013 (EPUB MOBI PDF)
    • Deployment guide for SharePoint 2013 (EPUB MOBI PDF)
    • Test Lab Guide: eBook for SharePoint Server 2013 Intranet and Team Sites (EPUB MOBI PDF DOC)
    • Create a Balanced Scorecard (SharePoint Server 2010) (EPUB MOBI PDF)
    • SharePoint Server for Business Intelligence (EPUB MOBI PDF)
    • Getting started with Microsoft SharePoint Foundation 2010 (PDF)
    • Technical reference for Microsoft SharePoint Server 2010 (PDF)
    • Governance guide for Microsoft SharePoint Server 2010 (PDF EPUB MOBI)
    • Profile synchronization guide for SharePoint Server 2010 (PDF EPUB MOBI)
    • Remote BLOB storage for Microsoft SharePoint Server 2010 (PDF EPUB MOBI)
    • Planning guide for sites and solutions for Microsoft SharePoint Server 2010, Part 1 (PDF DOC XPS)
    • Planning guide for sites and solutions for Microsoft SharePoint Server 2010, Part 2 (PDF DOC XPS)
    • Planning guide for server farms and environments for Microsoft SharePoint Server 2010 (PDF XPS DOC)
    • Capacity planning for Microsoft SharePoint Server 2010 (PDF XPS DOC)
    • Extracting and Loading SharePoint Data in SQL Server Integration Services (EPUB MOBI PDF)
    • Planning Disaster Recovery for Microsoft SQL Server Reporting Services in SharePoint Integrated Mode (EPUB MOBI PDF)
    • Deployment guide for Duet Enterprise for Microsoft SharePoint and SAP Server 2.0 Preview
      (PDF)

HOW TO BUY ,CREATE & HOST OR DEPLOY YOUR OWN WEBSITE

Introduction A website is a collection of Web pages, images, videos or other digital assets that is hosted on...