Thursday, November 29, 2012

Email Sending method


using System.Net.Mail;
private void SendEmails(string to, string from, string cc, string bcc, string subject, string message, string smtpAddress)
        {
            try
            {
 
                char emailSeperator = Convert.ToChar(',');
                WriteLog("From:" + from);
                WriteLog("To:" + to);
                WriteLog("CC:" + cc);
                WriteLog("BCC:" + bcc);
                MailMessage msgMail = new MailMessage();
                string[] arrToEmail = to.Split(emailSeperator);
                foreach (string toEmail in arrToEmail)
                {
                    msgMail.To.Add(toEmail);
                }
                if (!string.IsNullOrEmpty(cc.Trim()))
                {
                    string[] arrCCEmail = cc.Split(emailSeperator);
                    foreach (string ccEmail in arrCCEmail)
                    {
                        msgMail.CC.Add(ccEmail);
                    }
 
                }
                if (!string.IsNullOrEmpty(bcc.Trim()))
                {
                    string[] arrBCCEmail = bcc.Split(emailSeperator);
                    foreach (string bccEmail in arrBCCEmail)
                    {
                        msgMail.Bcc.Add(bccEmail);
                    }
 
                }
                msgMail.IsBodyHtml = true;
                msgMail.From = new MailAddress(from);
                msgMail.Subject = subject;
                msgMail.Body = message;
                SmtpClient SmtpSend = new SmtpClient(smtpAddress);
                try
                {
                    SmtpSend.Send(msgMail);
                    WriteLog("***************************");
                    WriteLog("Email sent to : " + to + " , Email sent from : " + from + " , Subject : " + subject);
                    WriteLog("***************************");
                }
                catch (Exception ex)
                {
                    LogMessage(ex);
                }
            }
            catch (Exception ex)
            {
                LogMessage(ex);
            }
 
        }

Exception Handling in .net and Sharepoint


using System.IO;
using Microsoft.SharePoint.Administration;

//Below are the methods can be used to log exception in files or in ULS logs
private void WriteLog(string LogText)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    string fullFileName = GetValueByKey(CONFIG_LOG_FILEPATH);
                    string folderpath = string.Empty;
                    string fileName = string.Empty;
                    string ext = string.Empty;
 
                    string file = fullFileName;
 
                    folderpath = file.Remove(file.LastIndexOf("\\") + 1);
                    fileName = file.Substring(file.LastIndexOf("\\") + 1);
                    ext = fileName.Substring(fileName.LastIndexOf("."));
                    fileName = fileName.Remove(fileName.LastIndexOf("."));
 
                    string LogFilePath = folderpath + fileName + ext; ;
                    if (File.Exists(fullFileName))
                    {
                        FileInfo fi = new FileInfo(fullFileName);
                        long size = fi.Length;
 
                        if (size > 10485760)
                        {
                            string date = DateTime.Today.Year.ToString() + DateTime.Today.Month.ToString() + DateTime.Today.Day.ToString();
                            string time = DateTime.Now.TimeOfDay.Hours.ToString() + DateTime.Now.TimeOfDay.Minutes.ToString() + DateTime.Now.TimeOfDay.Seconds.ToString();
                            string dateTime = date + "T" + time;
                            string newPath = folderpath + fileName + "_" + dateTime + ext;
                            File.Copy(LogFilePath, newPath);
                            File.Delete(LogFilePath);
 
                        }
                    }
 
                    StreamWriter SW;
 
                    SW = File.AppendText(LogFilePath);
                    SW.WriteLine(DateTime.Now + ":~Workflow Round 2~:" + LogText);
                    SW.Close();
                });
 
            }
            catch (Exception ex)
            {
                LogMessage(ex);
 
            }
        }
 
        /// <summary>
        /// Private method Logs Error Message
        /// </summary>
        /// <param name="severity">TraceSeverity severity</param>
        /// <param name="message">String Message</param>
        private void LogMessage(TraceSeverity severity, string message)
        {
            try
            {
                uint uintEventID = 8000;//event ID
                string CategoryName = "Log Message";
                SPDiagnosticsCategory category = new SPDiagnosticsCategory(CategoryName, TraceSeverity.Medium, EventSeverity.Error);
                SPDiagnosticsService.Local.WriteTrace(uintEventID, category, TraceSeverity.Unexpected, message);
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message.ToString());
                LogMessage(ex);
 
            }
 
 
        }
        /// <summary>
        /// Log Error Message
        /// </summary>
        /// <param name="ex">Exception ex</param>
        public void LogMessage(Exception ex)
        {
            LogMessage(TraceSeverity.High, ex.Message + ex.StackTrace);
        }
        /// <summary>
        /// Log Message
        /// </summary>
        /// <param name="message">string</param>
        public void LogMessage(string message)
        {
            LogMessage(TraceSeverity.Medium, message);
        }

Common methods to perform CRUD operation through C#


//Create a .cs file to access common method
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
 
using Microsoft.ApplicationBlocks.Data;// this Microsoft.ApplicationBlocks.Data.dll file shou                                                                  ld be downloaded
using Common;
using Common.Settings;
using Common.Exceptions;
 
namespace Common.Data
{
    public class BaseDataAccess
    {
        private const string CONNECTION_STRING_PARAM = "ConnectionString";
 
        private static string _connectionString = ConfigSettings.GetProperty(CONNECTION_STRING_PARAM);
       
        private string          _commandText;
        private string          _spName;
        private SqlParameter[]  _sqlParameter;
        private CommandType     _commandType;
        private SqlDataReader _reader;
         private int _result;
        
        public BaseDataAccess()
        {
            //
        }
        public BaseDataAccess(string commandText)
        {
            _commandText = commandText;
        }
        public BaseDataAccess(string spName, SqlParameter[] inputParam)
        {
            _spName = spName;
            _sqlParameter = inputParam;
        }
 
 
        public string getConnectionString()
        {
            return _connectionString;
        }
        public void setConnectionString(string connectionString)
        {
            _connectionString = connectionString;
        }
 
        public string getCommandText()
        {
            return _commandText;
        }
        public void setCommandText(string commandText)
        {
            _commandText = commandText;
        }
 
        public string getStoredProcedureName()
        {
            return _spName;
        }
        public void setStoredProcedureName(string spName)
        {
            _spName = spName;
        }
 
        public SqlParameter[] getInputParam()
        {
            return _sqlParameter;
        }
        public void setParam(SqlParameter[] sqlParameter)
        {
            _sqlParameter = sqlParameter;
        }
 
        public CommandType getCommandType()
        {
            return _commandType;
        }
        public void setCommandType(CommandType commandType)
        {
            _commandType = commandType;
        }
 
        // Read 
 
        public SqlDataReader read(string sqlCommandText)
        {
             
             try
            {
                _reader = SqlHelper.ExecuteReader(_connectionString, CommandType.Text, sqlCommandText);
            }
            catch (Exception ex)
            {
                AppException.HandleException(ex);
            }
            return _reader;
        }
 
        public StoredProcedureDataReader read(string storedProcedureName, SqlParameter[] sqlParameter)
        {
             StoredProcedureDataReader _spreader = new StoredProcedureDataReader();
             try
            {
                _spreader = getStoredProcedureDataReader(storedProcedureName, sqlParameter);
            }
            catch (Exception ex)
            {
                AppException.HandleException(ex);
            }
            return _spreader;
        }
         public StoredProcedureDataReader Execute(string storedProcedureName, SqlParameter[] sqlParameter)
         {
              StoredProcedureDataReader _spreader = new StoredProcedureDataReader();
              try
              {
                   _spreader = getStoredProcedureDataReader(storedProcedureName, sqlParameter);
              }
              catch (Exception ex)
              {
                   AppException.HandleException(ex);
              }
              return _spreader;
         }
 
        // Insert
        public int insert(string sqlCommandText)
        {
            try
            {
                _result =  SqlHelper.ExecuteNonQuery(_connectionString, CommandType.Text, sqlCommandText);
            }
            catch (Exception ex)
            {
                AppException.HandleException(ex);
            }
            return _result;
        }
        public int insert(string spName, SqlParameter[] sqlParameter)
        {
            try
            {
                _result = SqlHelper.ExecuteNonQuery(_connectionString, CommandType.StoredProcedure, spName, sqlParameter);
            }
            catch (Exception ex)
            {
                AppException.HandleException(ex);
            }
            return _result;
        }
        
        // Update
        public int update(string sqlCommandText)
        {
            try
            {
                _result = SqlHelper.ExecuteNonQuery(_connectionString, CommandType.Text, sqlCommandText);
            }
            catch (Exception ex)
            {
                AppException.HandleException(ex);
            }
            return _result;
        }
 
        public int update(string spName, SqlParameter[] sqlParameter)
        {
            try
            {
                _result = SqlHelper.ExecuteNonQuery(_connectionString, CommandType.StoredProcedure, spName, sqlParameter);
            }
            catch (Exception ex)
            {
                AppException.HandleException(ex);
            }
            return _result;
        }
        
        // Delete
 
        public int delete(string sqlCommandText)
        {
            try
            {
                _result = SqlHelper.ExecuteNonQuery(_connectionString, CommandType.Text, sqlCommandText);
            }
            catch (Exception ex)
            {
                AppException.HandleException(ex);
            }
            return _result;
        }
        
        public int delete(string spName, SqlParameter[] sqlParameter)
        {
            try
            {
                _result = SqlHelper.ExecuteNonQuery(_connectionString, CommandType.StoredProcedure, spName, sqlParameter);
            }
            catch (Exception ex)
            {
                AppException.HandleException(ex);
            }
            return _result;
            
        }
        // This method will return all the parameters defind for the stored procedure
        public SqlParameter[] getSpParameterSet(string spName)
        {
            try
            {
                _sqlParameter = SqlHelperParameterCache.GetSpParameterSet(_connectionString, spName);
            }
            catch (Exception ex)
            {
                AppException.HandleException(ex);
            }
            return _sqlParameter;
        }
 
        // This method is written to read the output parameters. SQL Helper class is not returning the
        // output parameters.
 
        private StoredProcedureDataReader getStoredProcedureDataReader(string spName, SqlParameter[] sqlParameter)
        {
            StoredProcedureDataReader _spDatareader = new StoredProcedureDataReader();
            SqlConnection cnn = new SqlConnection(_connectionString);
            SqlCommand cmd = new SqlCommand();
            SqlDataReader dr;
 
            try
            {
                cmd.Connection = cnn;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = spName;
                
                if (sqlParameter != null)
                {
                    foreach (SqlParameter param in sqlParameter)
                    {
                        cmd.Parameters.Add(param);
                    }
                }
 
                cnn.Open();
 
                dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
 
                _spDatareader.setSqlDataReader(dr);
                
                 if (sqlParameter != null)
                    _spDatareader.setSqlParameter(sqlParameter);                
            }
            catch (Exception ex)
            {
                AppException.HandleException(ex);
            }
            finally
            {
                cmd.Dispose();
            }
 
            return _spDatareader;
        }
 
 
        public class StoredProcedureDataReader
        {
            SqlDataReader _reader;
            SqlParameter[] _sqlParameter;
 
            public SqlDataReader getSqlDataReader()
            {
                return _reader;
            }
            public void setSqlDataReader(SqlDataReader reader)
            {
                _reader = reader;
            }
 
            public SqlParameter[] getSqlParameter()
            {
                return _sqlParameter;
            }
            public void setSqlParameter(SqlParameter[] sqlParameter)
            {
                _sqlParameter = sqlParameter;
            }
        }
 
        public SqlDataReader executeWithTransaction(string spName, SqlParameter[] sqlParameter, SqlTransaction transaction)
        {
            try
            {
                _reader = SqlHelper.ExecuteReader(transaction, CommandType.StoredProcedure, spName, sqlParameter);
            }
            catch (Exception ex)
            {
                AppException.HandleException(ex);
            }
 
            return _reader;
        }
 
        public DataTable GetRecords(string storedProcedureName, SqlParameter[] parameters)
        {
            SqlConnection sqlCon = new SqlConnection(_connectionString);
            DataSet dataSetRecord = new DataSet();
            SqlCommand sqlCmd = new SqlCommand();
            SqlDataAdapter dataAdapter;
            sqlCmd.Connection = sqlCon;
            sqlCmd.CommandText = storedProcedureName;
            sqlCmd.CommandType = CommandType.StoredProcedure;
            foreach (SqlParameter param in parameters)
            {
                sqlCmd.Parameters.Add(param);
            }
            try
            {
 
                dataAdapter = new SqlDataAdapter(sqlCmd);
                dataAdapter.Fill(dataSetRecord, "Result");
            }
            catch (Exception ex)
            {
                AppException.HandleException(1, ex.Message, ex);
            }
            finally
            {
                sqlCon.Close();
            }
            return dataSetRecord.Tables["Result"];
        }
    }
}






//After creating above .cs file add the below code to perform CRUD operation.

 public void insertUpdate()
        {
            StoredProcedureDataReader reader = new StoredProcedureDataReader();
            try
            {
 
                _sqlParameter = getSpParameterSet("ProcName");
               
                _sqlParameter[0].Value ="Value";
                
                reader = Execute("ProcName", _sqlParameter);
                _reader = reader.getSqlDataReader();
 
                if (_reader == null)
                    return string.empty;
 
                if (_reader.HasRows)
                {
                    if (_reader.Read())
                    {
                        string value = Convert.ToInt64(_reader.GetValue(0));
 
                    }
                }
            }
            catch (Exception ex)
            {
 
                throw ex;
            }
            finally
            {
                if (_reader != null)
                {
                    _reader.Close();
                    _reader.Dispose();
                }
                reader = null;
                _sqlParameter = null;
            }
            
        }



public void getDetailList()
        {
            List<DoctorShare> lstDoctorShare = new List<DoctorShare>();
            StoredProcedureDataReader reader = new StoredProcedureDataReader();
            DoctorShare objDoctorShare = null;
            try
            {
 
                _sqlParameter = getSpParameterSet("Proc Name");
                
                    _sqlParameter[0].Value = "value";
               
 
                reader = Execute("Proc Name", _sqlParameter);
                _reader = reader.getSqlDataReader();
 
                if (_reader == null)
                    return lstDoctorShare;
 
                if (_reader.HasRows)
                {
                    while (_reader.Read())
                    {
                        
                        string value = Convert.ToInt64(_reader.GetValue(0));
                      
 
                    }
                }
            }
            catch (Exception ex)
            {
 
                throw ex;
            }
            finally
            {
 
                _reader.Close();
                _reader.Dispose();
                reader = null;
                _sqlParameter = null;
            }
            
        }


public int delete()
        {
            int _result = 0;
            try
            {
                
                    _sqlParameter = getSpParameterSet("ProcName");
                    _sqlParameter[0].Value = "value";
 
 
                    _result = insert("ProcName", _sqlParameter);
                }
            }
            catch (Exception ex)
            {
                AppException.HandleException(ex);
            }
            finally
            {
                _sqlParameter = null;
            }
            return _result;
        }

Sunday, August 5, 2012

PowerShell Commands-Part 4


SharePoint Powershell Commands

SPTaxonomySession
Get-SPTaxonomySession – Get a TaxonomySession instance
SPTimerJob
Disable-SPTimerJob
Enable-SPTimerJob
Get-SPTimerJob
Set-SPTimerJob
Start-SPTimerJob
SPTopologyWebServiceApplication
Get-SPTopologyWebServiceApplication
Set-SPTopologyWebServiceApplication
SPTopologyWebServiceProxy
Get-SPTopologyWebServiceProxy
Set-SPTopologyWebServiceProxy
SPUsageApplication
Get-SPUsageApplication
New-SPUsageApplication
Remove-SPUsageApplication
Set-SPUsageApplication
SPUsageDefinition
Get-SPUsageDefinition
Set-SPUsageDefinition
SPUsageLogFile
New-SPUsageLogFile
SPUsageService
Get-SPUsageService
Set-SPUsageService
SPUser
Get-SPUser – Returns the user(s) that match a given search criteria.
Move-SPUser – Migrates a user account in .
New-SPUser – Adds an existing user to a site with the designated permissions.
Remove-SPUser – Removes a user from a web site.
Set-SPUser – Configures properties on an existing user.
SPUserProfilePhotoStore
Update-SPUserProfilePhotoStore
SPUserSolution
Add-SPUserSolution
Get-SPUserSolution
Install-SPUserSolution
Remove-SPUserSolution
Uninstall-SPUserSolution
Update-SPUserSolution
SPVisioExternalData
Get-SPVisioExternalData – Returns the settings for external data connections for a Visio Service application.
Set-SPVisioExternalData
SPVisioPerformance
Get-SPVisioPerformance – Returns the Visio Graphics Services settings for the performance of a Visio Service application.
Set-SPVisioPerformance – Sets performance properties for a Visio Services application.
SPVisioSafeDataProvider
Get-SPVisioSafeDataProvider – Returns the settings of a safe data provider for a Visio Services application.
New-SPVisioSafeDataProvider – Adds a new data provider to a Visio Services application.
Remove-SPVisioSafeDataProvider – Removes a data provider from a Visio Services application.
Set-SPVisioSafeDataProvider – Specifies a description of a safe data provider for a Visio Services application.
SPVisioServiceApplication
Get-SPVisioServiceApplication – Returns properties of a Visio Services application or a collection of Visio Services applications.
New-SPVisioServiceApplication – Adds a new Visio Services application to a farm.
Remove-SPVisioServiceApplication – Removes a Visio Services application from a farm.
Set-SPVisioServiceApplication – Sets the ServiceApplicationPool property of a Visio Services application.
SPVisioServiceApplicationProxy
Get-SPVisioServiceApplicationProxy – Returns properties of a Visio Services application proxy or a collection of Visio Services application proxies.
New-SPVisioServiceApplicationProxy – Adds a new Visio Services application proxy to a farm.
Remove-SPVisioServiceApplicationProxy – Removes a Visio Services application proxy from a farm.
SPWeb
Export-SPWeb – Exports a site collection, Web application, list, or library.
Get-SPWeb – Returns all sub-sites that match the given criteria.
Import-SPWeb – Imports a site collection, Web application, list, or library.
New-SPWeb – Creates a new sub-site under any existing site collection.
Remove-SPWeb – Completely deletes the specified Web.
Set-SPWeb – Configures the specified sub-site.
SPWebAnalyticsServiceApplication
Get-SPWebAnalyticsServiceApplication – Returns the settings for a Web Analytics Service application.
New-SPWebAnalyticsServiceApplication – Adds a new Web Analytics Service application to the farm.
Set-SPWebAnalyticsServiceApplication – Sets properties of a Web Analytics Service application.
SPWebAnalyticsServiceApplicationProxy
New-SPWebAnalyticsServiceApplicationProxy – Adds a new Web Analytics Service application proxy to the farm.
SPWebApplication
Get-SPWebApplication – Returns all Web applications that match the given criteria.
New-SPWebApplication – Creates a new Web application within the local farm.
Remove-SPWebApplication – Deletes the specified Web application.
Set-SPWebApplication – Configure the specified Web application.
SPWebApplicationExtension
New-SPWebApplicationExtension – Creates a new zone instance for the Web application.
SPWebApplicationHttpThrottling
Disable-SPWebApplicationHttpThrottling
Enable-SPWebApplicationHttpThrottling
SPWebApplicationHttpThrottlingMonitor
Set-SPWebApplicationHttpThrottlingMonitor
SPWebApplicationHttpThrottlingMonitors
Get-SPWebApplicationHttpThrottlingMonitors
SPWebApplicationSiginRedirectUrl
Set-SPWebApplicationSiginRedirectUrl
SPWebPartPack
Get-SPWebPartPack – Return the Web part packages installed for the specified scope.
Install-SPWebPartPack – Installs the specified Web part package to the specified location.
Uninstall-SPWebPartPack – Uninstall the specified Web part package.
SPWebTemplate
Get-SPWebTemplate – Displays all globally installed site templates that match the given identity.
Install-SPWebTemplate – Installs the given site template.
Set-SPWebTemplate – Changes the title and description of an installed site template.
Uninstall-SPWebTemplate – Uninstall the given site template.
SPWordConversionServiceApplication
New-SPWordConversionServiceApplication – Creates a new service application.
Set-SPWordConversionServiceApplication – Sets parameters on a service application.
SPWordConversionServiceApplicationProxy
New-SPWordConversionServiceApplicationProxy – Creates a new service application proxy.
SPWorkflowConfig
Get-SPWorkflowConfig – Returns workflow settings for the specified Web application.
Set-SPWorkflowConfig – Configures the workflow settings for the specified Web application.