Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Sunday 22 June 2014

Dynamically Bind SharePoint List Items to Gridview

public void BindDataTable(string LstName, SPListItem Item)
        {
            SPList lst = oWeb.Lists["LstName"];
            SPQuery M_Query = new SPQuery();
            StringBuilder sbQuery = new StringBuilder();
            sbQuery.Append("<Where>");
            sbQuery.Append("<Eq>");
            sbQuery.Append("<FieldRef Name='Title' />");
            sbQuery.Append("<Value Type='Text'>" + LstName + "</Value>");
            sbQuery.Append("</Eq>");
            sbQuery.Append("</Where>");
            M_Query.Query = sbQuery.ToString();
            SPListItemCollection lst_colls = lst.GetItems(M_Query);
            if (lst_colls.Count > 0)
            {
                string[] columnArr = lst_colls[0]["Columns"].ToString().Split(',');
               
                DataTable table;
                table = new DataTable();
                foreach (string Column in columnArr)
                {
                    table.Columns.Add(Column, typeof(string));
                }
                DataRow row = table.Rows.Add();
                foreach (string Column in columnArr)
                {
                    row[Column] = Convert.ToString(Item[Column]);
                }
                rptViewReq.DataSource = table.AsDataView();
                rptViewReq.DataBind();
            }

Add SharePoint List Items To C# List Programmatically

 private List<string> GetListItems()
        {
            //string[] ListArr = { string.Empty };
            List<string> list = null;
            try
            {
                SPList lst = Web.Lists["ListName"];
                SPListItemCollection lst_colls = lst.Items;
                if (lst_colls.Count > 0)
                {
                  
                    list = new List<string>();
                    foreach (SPListItem Item in lst_colls)
                    {
                        if (!string.IsNullOrEmpty(Convert.ToString(Item["Title"])))
                        {
                            list.Add(Convert.ToString(Item["Title"]));
                        }
                    }
                   
                }
                return list;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Define javaScript in Codebehind and Call on Events for SharePoint Modal Dialogbox

commenturl.NavigateUrl = "javascript:ShowPage('" + SPContext.Current.Web.Url + "/SitePages/Sample.aspx?ID=" + id + "')"; ;

 private string GetScript()
        {
            string script = string.Concat("<script type='text/javascript'>",
                            "ExecuteOrDelayUntilScriptLoaded(ShowPage, 'sp.js');",
                            "function ShowPage(URL)        ",
                            " {var options = SP.UI.$create_DialogOptions();",
                        "options.url=URL;",
                        "options.title='Delegate';",
                            "options.autoSize = true;",
                            "options.showClose=true;",
                            "options.allowMaximize=false;",
                            "options.dialogReturnValueCallback= Function.createDelegate(null,DialogCallBack);",
                            "SP.UI.ModalDialog.showModalDialog(options);}",
                            "function DialogCallBack(dialogResult, returnValue) ",
                            "{ if (dialogResult== SP.UI.DialogResult.cancel){",
                                "var notifyId = SP.UI.Notify.addNotification('Message cancelled', false);",
                                "window.location.href='/SitePages/Home.aspx';",
                                "SP.UI.ModalDialog.close(dialogResult);    }",
                                "if (dialogResult== SP.UI.DialogResult.OK)",
                                "{ window.location.href='/SitePages/Home.aspx';",
                                "SP.UI.ModalDialog.close(dialogResult);    ",
                                "}};</script>");
            return script;

        }

Call this script in Page Load:

ScriptManager.RegisterStartupScript(this.Page, GetType(), "popup", GetScript(), false);

Send Email Template By Using Hashtable

        Hashtable MailContents = new Hashtable();
                MailContents["[[Outcome]]"] = "Approved";
                MailContents["[[Approver]]"] = Approver.Name;
                MailContents["[[Subject]]"] = "A Request is Approved by " + Approver.Name;
                MailContents["[[To]]"] = Convert.ToString(Author.Email);
                MailContents["[[User]]"] = Author.Name;
                MailContents["[[Comments]]"] = txtCommnets.Text;
                MailContents["[[Link]]"] = URL.Remove(0, 7);
                SendEmailFromTemplate("key", MailContents, SPContext.Current.Web.Url);
                MailContents.Clear();
               
 public static void SendEmailFromTemplate(string KeyName, Hashtable KeyValue, string SiteUrl)
        {
            try
            {
               
                SPItem itemMailTemplate = getMailTemplate(KeyName, SiteUrl);

                string strFrom = Convert.ToString(itemMailTemplate["From"]);
                string strTo = Convert.ToString(itemMailTemplate["To"]);
                string strCc = Convert.ToString(itemMailTemplate["CC"]);
                string strSubject = Convert.ToString(itemMailTemplate["Subject"]);
                string strBody = Convert.ToString(itemMailTemplate["Body"]);
                // Check if From Field is Dynamic
                if (strFrom.Contains("[[From]]"))
                {
                    strFrom = strFrom.Replace("[[From]]", Convert.ToString(KeyValue["[[From]]"]));
                }
                // Check if To Field is Dynamic
                if (strTo.Contains("[[To]]"))
                {
                    strTo = strTo.Replace("[[To]]", Convert.ToString(KeyValue["[[To]]"]));
                }
                // Check if CC Field is Dynamic
                if (strCc.Contains("[[CC]]"))
                {
                    strCc = strCc.Replace("[[CC]]", Convert.ToString(KeyValue["[[CC]]"]));
                }
                foreach (DictionaryEntry Item in KeyValue)
                {
                    strSubject = strSubject.Replace(Item.Key.ToString(), Convert.ToString(Item.Value));
                    strBody = strBody.Replace(Item.Key.ToString(), Convert.ToString(Item.Value));
                }

                SendEmail(strFrom, strTo, strCc, string.Empty, strSubject, strBody, null, null);
            }
            catch (Exception ex)
            {
                throw ex;
            }


        }

 protected static SPItem getMailTemplate(string key, string siteUrl)
        {
            SPItem itemMailTemplate = null;
            try
            {
                using (SPSite site = new SPSite(siteUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists["TempltesList"];
                        SPQuery query = new SPQuery();
                        query.Query = "<OrderBy>" +
                                        "<FieldRef Name='Value' />" +
                                      "</OrderBy>" +
                                      "<Where>" +
                                             "<Eq>" +
                                                  "<FieldRef Name='Title' />" +
                                                  "<Value Type='Text'>" + key + "</Value>" +
                                             "</Eq>" +
                                       "</Where>";
                        SPListItemCollection itemColl = list.GetItems(query);
                        if (itemColl != null && itemColl.Count > 0)
                        {
                            itemMailTemplate = itemColl[0];
                        }
                        else
                        {
                            throw new Exception("Key doesn't exist in the TempltesList ");
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
            return itemMailTemplate;
        }         


 public static void SendEmail(string from, string to, string cc, string bcc, string subject, string body, SPFolder attachments, string SMTPServer)
        {
            try
            {
                if (string.IsNullOrEmpty(SMTPServer))
                    SMTPServer = SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address;

                SmtpClient client = new SmtpClient(SMTPServer);
                MailMessage mail = new MailMessage();
                string[] strArrTo = to.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                string[] strArrCC = cc.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                string[] strArrBCC = bcc.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);

                client.UseDefaultCredentials = true;
                client.EnableSsl = false;
                if (string.IsNullOrEmpty(from))
                {
                    from = SPAdministrationWebApplication.Local.OutboundMailSenderAddress;
                }
                mail.From = new MailAddress(from);
                mail.Subject = subject;
                mail.Body = body;
                mail.IsBodyHtml = true;

                foreach (string strTo in strArrTo)
                {
                    if (!string.IsNullOrEmpty(strTo))
                    {
                        mail.To.Add(new MailAddress(strTo));
                    }
                }

                foreach (string strCC in strArrCC)
                {
                    if (!string.IsNullOrEmpty(strCC))
                    {
                        mail.CC.Add(new MailAddress(strCC));
                    }
                }
                foreach (string strBCC in strArrBCC)
                {
                    if (!string.IsNullOrEmpty(strBCC))
                    {
                        mail.Bcc.Add(new MailAddress(strBCC));
                    }
                }
                if (attachments != null && attachments.Files.Count > 0)
                {
                    try
                    {
                        foreach (SPFile file in attachments.Files)
                        {
                            mail.Attachments.Add(new Attachment(file.OpenBinaryStream(), file.Name));
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;  }
                }


                client.Send(mail);
            }

            catch (SmtpException ex)
            {
                throw ex;
            }

            catch (InvalidOperationException ioe)
            {
                throw ioe;
            }
        }

CSS to Get Curved Corners For SharePoint Modal Dialogbox

<style type="text/css">
.ms-dlgOverlay {background:#fff;}

/* set rounded corners */
.ms-dlgContent, .ms-dlgBorder, .ms-dlgTitle {
  -webkit-border-top-right-radius: 12px;
  -webkit-border-top-left-radius: 12px;
          border-top-right-radius: 12px;
          border-top-left-radius: 12px;
  -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box;
    background:#333;

}
/* give both divs a 1px border to erase strange padding */
.ms-dlgBorder, .ms-dlgContent {border:1px solid #333;}

/* add a drop shadow to the outermost div */
.ms-dlgBorder {
  -webkit-box-shadow: 3px 3px 10px -3px #333;
          box-shadow: 3px 3px 10px -3px #333;
}

/* take away borders and then
add back in a bottom border to separate title from ribbon */
.ms-dlgTitle {
    border:none;
    border-bottom:1px solid #fff;
}
/* color text of title of modal */
.ms-dlgTitleText {color:#fff;}

</style>

Simple javaScript to Show a page as modal Dialogbox in SharePoint

Add Content Editor WebPart to Sample.aspx page and add following Code to it

<a href="javascript:var options = {
            url: '/sitepages/Sample.aspx',
            title: 'Title, Description, and Icon',
            width: 640,
            height: 400
        }

        SP.UI.ModalDialog.showModalDialog(options);
;">Show Me the Pop-Up!</a>

Check current User is MemberofGroup or Not?

        SPGroupCollection groupColl = SPContext.Current.Web.SiteGroups;
            SPGroup grp = groupColl["grp1"];
            if (SPContext.Current.Web.IsCurrentUserMemberOfGroup(grp.ID))
                GRP = grp1;
            else
                GRP = "grp2";

CSS To hide Page Tab in SharePoint ModalDialogBox

<style type="text/css">
body{overflow:auto !important;}
#s4-leftpanel { display: none;}
.s4-ca {margin-left:0px !important;}
#s4-ribbonrow{height:auto !important;min-height:0px !important;}
#s4-ribboncont{display:none;}
#s4-titlerow{ display:none;}
.s4-ba {width:100%; min-height:0px !important;}
#s4-workspace{float:left;width:100%; overflow:auto  !important;}
body #MSO_ContentTable{min-height:0px !important;position:inherit;}
</style>

CSS to Change SharePoint ModalDialogBox Title Background

<style type="text/css">
.ms-dlgOverlay
    {
        background-color: #676767;
    }
    .ms-dlgContent
    {
        border: 0;
    }
    .ms-dlgBorder
    {
        border: 1px solid #0087C1;
    }
    .ms-dlgTitle
    {
        background-color: #0087C1;
    }
    .ms-dlgTitleText
    {
        display: block;
        font-weight: bold;
        font-size: 13px;
        padding: 7px;
    }
</style>

Upload Attachments with html upload control when asp.net upoload control presence To SharePoint Document library Programmatically

 private void UploadOtherAttachments()
        {
            try
            {
                    HttpFileCollection hfcFiles = Request.Files;
                    if (hfcFiles.Count > 0)
                    {
                        for (int i = 0; i < Request.Files.Count; i++)
                        {
                            string[] Files;
                            bool Flag = false;
                            HttpPostedFile PostedFile = hfcFiles[i];
                            string RequestFilename = "";
                            if (PostedFile != null && PostedFile.FileName != String.Empty &&PostedFile.FileName!=(fuID.PostedFile.FileName) && PostedFile.ContentLength > 0)
                            {
                                RequestFilename = PostedFile.FileName;
                                string[] Separator = { "\\" };
                                if (PostedFile.FileName.Contains(Separator[0]))
                                {
                                    Files = PostedFile.FileName.Split(Separator, StringSplitOptions.None);
                                    RequestFilename = Files[Files.Length - 1];

                                }

                                string strInputFileName = Path.GetFileNameWithoutExtension(PostedFile.FileName)
                                                          + "_" + Path.GetExtension(PostedFile.FileName);

                                SPList docLibrary = Web.Lists["Library"];
                                SPFolder OAFolder = null;
                                foreach (SPListItem item in docLibrary.Folders)
                                {
                    SPFolder folder = item.Folder;
                                    if (folder.Name == "folder1")
                                    {
                                    OAFolder = "name of the folder";
                    }   
                                }
                                string docLibraryUrl = OAFolder.Url.ToString();
                                string destinationURL = docLibraryUrl + "/" + strInputFileName;

                                SPFile file = null;
                                file = docLibrary.RootFolder.Files.Add(destinationURL, PostedFile.InputStream, true);
                                SPListItem newItem = file.Item;
                                newItem["fld1"] = txt1.Text;
                                newItem["fld2"] = txt2.Text;
                                Web.AllowUnsafeUpdates = true;
                                newItem.Update();
                                file.Update();
                                web.AllowUnsafeUpdates = false;

                            }

                            else
                            {

                                //_Errormsg = "Request created..Relevant document upload failed";
                            }
                        }
                    }
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }

Import Excel Sheet as DataTable, Read Data from it

private decimal MethodName()
        {
            decimal amount = 0;
            DateTime ExpiryDate;
            try
            {
                if (fuID.HasFile && fuID.PostedFile.ContentLength > 0)
                {
                    string path = fuID.PostedFile.FileName;
                   
                    if (File.Exists(path))
                    {
            //convert excel to datatable

                        System.Data.DataTable dt = Common.ImportExcelXLS(path);
                        if (dt != null)
                        {
                            ViewState["Data"] = dt;
                            foreach (DataRow dr in dt.Rows)
                            {
                               
                                //do something
                            }
                        }
                   }
                }
            }
            catch (Exception ex)
            {
                //throw ex;
            }


            return amount;
            
        }

public static DataTable ImportExcelXLS(string fileLocation)
        {
            DataTable dt = new DataTable();
            DataTable dt1 = new DataTable();
            DataSet ds = new DataSet();
            using (OleDbConnection conn = new OleDbConnection())
            {
                string connectionString = string.Empty;
                try
                {
                    renameWorksheet(fileLocation);
                    if (Path.GetExtension(fileLocation) == ".xlsx")
                    {
                        StringBuilder sbConn = new StringBuilder();
                        sbConn.Append("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=");
                        sbConn.Append(fileLocation);
                        sbConn.Append(";Extended Properties='Excel 8.0;IMEX=1'");
                        connectionString = sbConn.ToString();
                        //"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties='Excel 8.0;IMEX=1'";
                    }
                    else
                    {
                        StringBuilder sbConn = new StringBuilder();
                        sbConn.Append("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=");
                        sbConn.Append(fileLocation);
                        sbConn.Append(";Extended Properties='Excel 8.0;IMEX=1'");

                        connectionString = sbConn.ToString(); //"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties='Excel 8.0;HDR=No;IMEX=1'";
                    }
                    conn.ConnectionString = connectionString;
                    if (conn.State != ConnectionState.Open)
                    {
                        conn.Open();
                    }
                    DataTable dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                    string sheetName = GetSheetName(dtSchema);

                    OleDbCommand cmd = new OleDbCommand("select * from [" + sheetName + "]", conn);
                    OleDbDataAdapter da = new OleDbDataAdapter(cmd);
                    dt.TableName = sheetName.Replace("$", "").Replace("'", "");
                    da.Fill(dt);

                    for (int h = 0; h < dt.Rows.Count; h++)
                    {
                        if (dt.Rows[h].IsNull(0) == true)
                        {
                            dt.Rows.Remove(dt.Rows[h]);
                        }
                    }
                }
                catch (Exception ex)
                {

                }
                finally
                {
                    conn.Close();
                }
                return dt;
            }

        }

 public static string GetSheetName(DataTable Dtschema)
        {
            List<string> sheetName = new List<string>();
            for (int i = 0; i < Dtschema.Rows.Count; i++)
            {
                if (!Dtschema.Rows[i].Field<string>("TABLE_NAME").ToString().Trim().ToUpper().Contains("FILTERDATABASE"))
                {
                    sheetName.Add(Dtschema.Rows[i].Field<string>("TABLE_NAME"));
                }
            }
            return sheetName[0].ToString();
        }

install 64bit AccessDataBaseEngine_64x.exe
Download from the following link:
http://www.microsoft.com/en-in/download/details.aspx?id=13255

Installation Steps:

Launching the install of a Microsoft ACE OLEDB Provider on a machine with an Office install other than the current one (e.g. 32 on 64) will cause the install to fail. To have it run properly you need to launch it from a command line with the “/passive” argument specified.
  • To install the Microsoft ACE OLEDB Provider 32-bit on a machine running Office 2010 64-bit:
$> AccessDatabaseEngine.exe /passive
  • To install the Microsoft ACE OLEDB Provider 64-bit on a machine running Office 2010 32-bit:
$> AccessDatabaseEngine_X64.exe /passive

Validation of Controls Using JavaScript


<script type="text/javascript">
    function validation() {
        try {
       
        //for textbox

            if (document.getElementById("<%= textboxID.ClientID %>").value == "") {
                alert('Please Enter Invoice Number');
                return false;
            }
            //for dropdown box

            if (document.getElementById("<%= ddlID.ClientID %>").selectedIndex == 0) { alert('Please Select Nature Of Service'); return false; }
           
        //for upload file control

            var File = document.getElementById("<%= fuID.ClientID %>");
            if (File.value == "") { alert('Please Select File For Upload'); return false; }

            var flag = false;
            var inputElements = document.getElementsByTagName('input');
            for (var i = 0; i < inputElements.length; i++) {
                var myElement = inputElements[i];
                if (myElement.type === "checkbox") {
                    if (myElement.checked) {
                        flag = true;
                        return true;
                    }
                }
            }
            if (flag == false) {
                alert('Please select option'); return false;
            }
           
        }
        catch (ex) { alert(ex.get_Message()); }
    }

</script>


In Design mode add this code:

<asp:Button ID="btnSubmit" runat="server" CssClass="btn" Text="Submit" OnClick="btnSubmit_Click"
                            OnClientClick="return validation();" />

Show Exception Message in java Script Alert in Code Behind


Page.ClientScript.RegisterStartupScript(GetType(), "Alert", @"<script language='javascript'>alert('" + ex.Message + @"');</script>");



Another Simple JavaScript Alert from Code Behind

ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "Alert", "alert('sometext*** sucessfully');", true);

 ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "Alert", "alert('sometext*** sucessfully');", true);
                    HttpContext context = HttpContext.Current;
                    context.Response.Write("<script type='text/javascript'>if(window.frameElement!=null){window.frameElement.commitPopup();}else{window.close();}</script>");
                    context.Response.Flush();
                    context.Response.End();

Export SharePoint List Data to Excel Sheet Programmatically

private void ExportToExcel(SPWeb _web)
        {
            if (_web != null)
            {

                SPList list = _web.Lists["InvoiceDetails"];
                if (list != null)
                {

                    DataTable dataTable = new DataTable();
                    //Adds Columns to SpreadSheet

                    InitializeExcel(list, dataTable);
                    string _schemaXML = list.DefaultView.ViewFields.SchemaXml;
                    if (list.Items != null && list.ItemCount > 0)
                    {

                        foreach (SPListItem _item in list.Items)
                        {

                            DataRow dr = dataTable.NewRow();

                            foreach (DataColumn _column in dataTable.Columns)
                            {

                                if (dataTable.Columns[_column.ColumnName] != null && _item[_column.ColumnName] != null)
                                {

                                    dr[_column.ColumnName] = _item[_column.ColumnName].ToString();

                                }

                            }

                            dataTable.Rows.Add(dr);
                        }

                        System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();
                        grid.HeaderStyle.Font.Bold = true;
                        grid.DataSource = dataTable;
                        grid.DataBind();
                        using (StreamWriter streamWriter = new StreamWriter("C:\\" + list.Title+ ".xls", false, Encoding.UTF8))
                        {

                            using (HtmlTextWriter htmlTextWriter = new HtmlTextWriter(streamWriter))
                            {

                                grid.RenderControl(htmlTextWriter);

                            }

                        }
                        ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "Alert", "alert('Excel file Created');", true);

                    }

                }

            }
        }

        public void InitializeExcel(SPList list, DataTable _datatable)
        {

            if (list != null)
            {
               
                string _schemaXML = list.DefaultView.ViewFields.SchemaXml;
               
                if (list.Items != null && list.ItemCount > 0)
                {

                   
                    foreach (SPListItem _item in list.Items)
                    {

                        foreach (SPField _itemField in _item.Fields)
                        {

                            if (_schemaXML.Contains(_itemField.InternalName))
                            {

                                if (_item[_itemField.InternalName] != null)
                                {

                                    if (!_datatable.Columns.Contains(_itemField.InternalName))
                                    {

                                        _datatable.Columns.Add(new DataColumn(_itemField.StaticName, Type.GetType("System.String")));

                                    }

                                }

                            }

                        }

                    }

                }

            }

        }

Friday 13 June 2014

JavaScript Alert in Code Behind


this.Page.ClientScript.RegisterStartupScript(Page.GetType(), "alert", "alert('You are not authorized user to view this page.');window.location='/SitePages/Welcome.aspx';", true);

Retrieve Attachments from SharePoint List Programmatically

private void RetrieveFile(SPListItem nitem)
        {
            DataTable dthref = new DataTable();
            dthref.Columns.Add("ViewFile", typeof(string));
            DataRow dataRow;
            dataRow = dthref.NewRow();
            foreach (String attachmentname in nitem.Attachments)
            {
                String attachmentAbsoluteURL = nitem.Attachments.UrlPrefix + attachmentname;
                //SPFile attachmentFile = SPContext.Current.Web.GetFile(attachmentAbsoluteURL);
                HtmlAnchor htmlanchor = new HtmlAnchor();
                htmlanchor.HRef = attachmentAbsoluteURL;
                dthref.Rows.Add(attachmentAbsoluteURL);
                // ViewState["attachmentFile"] = attachmentFile;
                ViewState["attachmentAbsoluteURL"] = attachmentAbsoluteURL;

            }

            dthref.AcceptChanges();
            gvFileView.Visible = true;
            gvFileView.DataSource = dthref;
            gvFileView.DataBind();
        }

Upload Attachments To SharePoint List Programmatically

  private void UploadFileToList(SPListItem itemToAdd)
        {
            using (SPSite oSite = new SPSite(siteURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                   
                        oWeb.AllowUnsafeUpdates = true;
                        if (fuOption.HasFile)
                        {
                            HttpFileCollection uploads = HttpContext.Current.Request.Files;
                            SPAttachmentCollection attachments;
                            for (int i = 0; i < uploads.Count; i++)
                            {
                                Stream fs = uploads[i].InputStream;
                                byte[] fileContents = new byte[fs.Length];
                                fs.Read(fileContents, 0, (int)fs.Length);
                                fs.Close();
                                attachments = itemToAdd.Attachments;
                                string fileName = Path.GetFileName(uploads[i].FileName);
                                attachments.Add(fileName, fileContents);
                            }
                        }
                        oWeb.AllowUnsafeUpdates = false;
                  
                }
            }
        }

Common DropDown Filling Code

 protected void FillDropDown()
        {
            try
            {
                string Query = @"<Where><IsNotNull><FieldRef Name='Title' /></IsNotNull></Where>";
                DataTable dt = GetDropdownItems("ListName", Query);
                BindDropdown(ddl, "Title", "Title", "", dt);
                ListItem objListItem = new ListItem("-- Please Select --", "");
                ddl.Items.Insert(0, objListItem);
            }
            catch (Exception ex)
            {
                ExceptionLog(ex);
            }
        }

private DataTable GetDropdownItems(string strListName, string strQuery)
        {
            DataTable dtSegment = null;
           
                SPQuery query = new SPQuery();
                query.Query = strQuery;
                SPSite spCurSite = SPContext.Current.Site;
                SPWeb web = spCurSite.OpenWeb();
                SPList list = web.Lists[strListName];
                SPListItemCollection itemColl = list.GetItems(query);
                dtSegment = itemColl.GetDataTable();

            return dtSegment;
        }

        private void BindDropdown(DropDownList ddl, string strDataTextField, string strDataValueField, string strDefaultVal, DataTable dtDropdownValues)
        {
           
                ddl.DataSource = dtDropdownValues;
                ddl.DataTextField = strDataTextField;
                ddl.DataValueField = strDataValueField;
                ddl.DataBind();
        }

To Deploy Visual WebPart to Particular Group In WebParts Group

<?xml version="1.0" encoding="utf-8" ?>
- <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
- <Module Name="ListName" List="113" Url="_catalogs/wp">
- <File Path="ListName\ListName.webpart" Url="ListName.webpart" Type="GhostableInLibrary">
  <Property Name="Group" Value="ur group name" />
  </File>
  </Module>
  </Elements>

Sample SharePoint TimerJob,Save Email Log to List Through Swith Case

Namespaces to add:

using System.Text;
using Microsoft.SharePoint.Administration;
using System.Data;
using System.IO;
using Microsoft.SharePoint;
using System.Net.Mail;
using System.Web.Configuration;
using System.Net;
using System.Collections.Specialized;
using System.Collections;
using Microsoft.SharePoint.Utilities;



namespace Sample
{
    class RemainderMail : SPJobDefinition
    {
        string siteURL = "ur sit url";
        public RemainderMail()
            : base()
        {
        }

        public RemainderMail(string jobName, SPService service, SPServer server, SPJobLockType targetType)
            : base(jobName, service, server, targetType)
        {
        }

        public RemainderMail(string jobName, SPWebApplication webApplication)
            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
        {
            this.Title = "Sending Remainder Mail TimerJob";
        }
        public override void Execute(Guid contentDbId)
        {
            SendingRemainderMails();
        }
        public void SendingRemainderMails()
        {
            using (SPSite oSite = new SPSite(siteURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    try
                    {
                        oWeb.AllowUnsafeUpdates = true;
                      
                        SPList oNotelist = oWeb.Lists["Noticelist"];
                        SPListItemCollection Notelisttemcoll = oRegNotelist.Items;

                        foreach (SPListItem item in regNotelisttemcoll)
                        {
                            string strMail = null;
                            if (Convert.ToString(item["NoticeStatus"]) == "Pending")
                            {
                                string noticeid = Convert.ToString(item["Title"]);
                               
                                SPGroup grp = oWeb.SiteGroups["Staff List"];

                                foreach (SPUser user in grp.Users)
                                {
                                    strMail = user.Email;
                                    sendEmail(strMail, noticeid);
                                }
                            }

                        }
                    }

                    catch (Exception ex)
                    {
                        ExceptionLog(ex);
                    }
                }
            }
        }
        protected void sendEmail(string strMail, string noticeid)
        {

            try
            {
                SmtpClient client = new SmtpClient();
                client.Host = "server name";
                NetworkCredential userCrendential = new NetworkCredential("username", "pwd");
                client.Credentials = userCrendential;
                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();

                string strBody = "";
                mail.From = new MailAddress("abc@abc.com", "Title");
                mail.Bcc.Add("abc@abc.com");
                mail.To.Add(strMail);
                mail.Subject = "--subject--";
                mail.Body = "Dear Sir/Madam," + "\r\n\n" + strBody + "\r\n" + siteURL + "SitePages/notice.aspx?NoticeID=" + noticeid + "\r\n\n\n\n" + "Thanks," + "\r\n" + "Team.";
                client.Send(mail);
                saveEmail("Sent", strMail,noticeid);
            }
            catch (Exception ex)
            {
                using (SPSite oSite = new SPSite(siteURL))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        saveEmail("Failed", strMail, noticeid);
                        ExceptionLog(ex);
                    }
                }
            }
        }

public void saveEmail(string emailStatus, string strMail, string noticeid)
        {
            using (SPSite oSite = new SPSite(siteURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    try
                    {

                        oWeb.AllowUnsafeUpdates = true;
                        SPUser oUser = oWeb.CurrentUser;
                        SPList lstEmail = oWeb.Lists["EMailLog"];
                        SPListItem itemadd = lstEmail.Items.Add();
                        SPFieldCollection fldColl = lstEmail.Fields;

                        StringDictionary headers = new StringDictionary();

                        string strBody = "";

                        headers.Add("to", strMail);
                        headers.Add("from", "ur email ");
                        headers.Add("subject", "title");
                        headers.Add("content-type", "text/html");

                        string bodyText = "Dear Sir/Madam," + "\r\n\n" + strBody + "\r\n" + siteURL + "SitePages/Notice.aspx?NoticeID=" + noticeid + "\r\n\n\n\n" + "Thanks," + "\r\n" +  Team.";
                        itemadd["Body"] = bodyText;

                        foreach (DictionaryEntry entry in headers)
                        {

                            switch (entry.Key.ToString())
                            {
                                case "to":
                                    itemadd["MailTo"] = entry.Value.ToString();
                                    break;
                                case "subject":
                                    itemadd["Subject"] = entry.Value.ToString();
                                    break;
                                case "content-type":
                                    itemadd["MessageType"] = entry.Value.ToString();
                                    break;
                                case "from":
                                    itemadd["Title"] = entry.Value.ToString();
                                    break;
                            }

                        }

                        itemadd["DateTime"] = DateTime.Now.ToShortDateString();
                        itemadd["Status"] = emailStatus;
                        itemadd.Update();
                        oWeb.AllowUnsafeUpdates = false;
                    }
                    catch (Exception ex)
                    {
                        ExceptionLog(ex);
                    }
                }
            }

        }
Please provide your feedback in the comments section above. Please don't forget to follow.