Wednesday, 4 March 2015

MVC Editable Grid

Employee Helper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MVCEditableGrid;
using MVCEditableGrid.Viewmodels;
using MVCEditableGrid.Models;
using System.Web.Mvc;
using System.Data;

namespace MVCEditableGrid.helpers
{
    public class EmployeeHelper : IDisposable
    {
        EmployeeEntities _dbconn = new EmployeeEntities();

        public List<EmlpyeesViewmodel> GetEmployees()
        {
            List<EmlpyeesViewmodel> EmployeeList = new List<EmlpyeesViewmodel>();
            EmployeeList = (from e in _dbconn.EmployeeMasters
                            join d in _dbconn.Departments on e.DeptId equals d.DeptId
                            select new EmlpyeesViewmodel
                            {
                                EmployeeId = e.EmployeeId,
                                EmployeeName = e.EmployeeName,
                                PhoneNumber = e.PhoneNumber,
                                DeptName = d.DeptName,
                                DeptId = d.DeptId
                            }).ToList();

            return EmployeeList;
        }

        public IEnumerable<SelectListItem> GetDepartment(int dept_Id)
        {
            List<SelectListItem> DepartmentList = new List<SelectListItem>();
            var department = _dbconn.Departments.ToList();
            department.ForEach(d => DepartmentList.Add(new SelectListItem() { Text = d.DeptName,Value = d.DeptId.ToString(),Selected = dept_Id == d.DeptId }));
            return DepartmentList;
        }

        public string Save(EmployeeMaster model)
        {
            if (model == null)
                return "Fail to update";
            else
            {
                try
                {
                    EmployeeMaster employee = _dbconn.EmployeeMasters.Where(e => e.EmployeeId == model.EmployeeId).SingleOrDefault();
                    _dbconn.Entry(employee).State = EntityState.Modified;
                    employee.EmployeeName = model.EmployeeName;
                    employee.PhoneNumber = model.PhoneNumber;
                    employee.DeptId = model.DeptId;
                    _dbconn.SaveChanges();
                    return "Success";
                }
                catch
                {
                    return "Fail to update";
                }
            }
         
        }

        #region IDisposable
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {

            if (disposing)
            {
                if (_dbconn != null) _dbconn.Dispose();
                _dbconn = null;
            }

        }
        #endregion
    }

}

EmployeeController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCEditableGrid.helpers;
using MVCEditableGrid.Viewmodels;

namespace MVCEditableGrid.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult EmployeeList()
        {
            return View();
        }


        public ActionResult GridView()
        {
            using (EmployeeHelper helper = new EmployeeHelper())
            {
                List<EmlpyeesViewmodel> EmployeeList = new List<EmlpyeesViewmodel>();
                EmployeeList = helper.GetEmployees();
                foreach (EmlpyeesViewmodel value in EmployeeList)
                {
                    value.Department = helper.GetDepartment(value.DeptId);

                }
                return View("GridView",EmployeeList);
            }
        }

        [HttpPost]
        public JsonResult save(EmployeeMaster model)
        {
            string message;
            using (EmployeeHelper helper = new EmployeeHelper())
            {
                message = helper.Save(model);
            }
            return Json(message, JsonRequestBehavior.AllowGet);

        }
    }

}

EmployeeList.cshtml
@*@model IEnumerable<MVCEditableGrid.Viewmodels.EmlpyeesViewmodel>*@
@{
    ViewBag.Title = "EmployeeList";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>EmployeeList</h2>
<div id="divgrid">
     @Html.Action("GridView")
</div>

GridView.cshtml
@model IEnumerable<MVCEditableGrid.Viewmodels.EmlpyeesViewmodel>
@{
    Layout = null;
}
<table>
    @foreach (var group in Model.GroupBy(x => x.DeptName))
    {
        <tr class="group-header" style="border-bottom: 1px solid">
            <td colspan="6">
                <span class="h3">@group.Key</span>
            </td>
        </tr>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.EmployeeName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.PhoneNumber)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.DeptName)
            </th>
            <th></th>
        </tr>
        foreach (var item in group)
        {
        <tr>
            <td>
                <div>
                    @Html.TextBoxFor(modelItem => item.EmployeeName, new { id = "txtEmployeeName", @class = "display-mode", @style = "display: none" })
                </div>
                @Html.Label(item.EmployeeName, new { id = "lblEmployeeName", @class = "edit-mode" })
            </td>
            <td>
                <div>
                    @Html.TextBoxFor(modelItem => item.PhoneNumber, new { id = "txtPhoneNumber", @class = "display-mode", @style = "display: none" })
                </div>
                @Html.Label(item.PhoneNumber, new { id = "lblPhoneNumber", @class = "edit-mode" })
            </td>
            <td>
                <div>
                    @Html.DropDownList("Department", item.Department, "", new { id = "DepartmentId", @class = "display-mode", @style = "display: none" })
                </div>
                @Html.HiddenFor(modelItem => item.DeptId, new { id = "hdnDeptId" })
                @Html.Label(item.DeptName, new { id = "lblDepartment", @class = "edit-mode" })
            </td>
            <td>
                @Html.HiddenFor(modelItem => item.EmployeeId, new { id = "hdnEmpId" })
                <a href="#" class="Editlink" onclick="Edit(this);" style="display: block">Edit</a>
                <a href="#" class="Savelink" onclick="Save(this);" style="display: none">Save</a>
                <a href="#" class="Cancellink" onclick="Cancel(this);" style="display: none">Cancel</a>
            </td>
        </tr>
        }
    }
</table>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script>
    function Edit(tag) {
        $(tag).siblings('a').show();
        $(tag).hide();
        var tr = $(tag).parents('tr');
        $('.display-mode').hide(); /// to show one editable row at a time
        $('.edit-mode').show();

        tr.find('.edit-mode').hide();
        tr.find('.display-mode').show();
    }

    function Cancel(tag) {
        var tr = $(tag).parents('tr');
        tr.find('#txtEmployeeName').val(tr.find('#lblEmployeeName').text());
        tr.find('#txtPhoneNumber').val(tr.find('#lblPhoneNumber').text());
        tr.find('#DepartmentId').val(tr.find('#hdnDeptId').val());
        tr.find('.edit-mode').show();
        tr.find('.display-mode').hide();
        $(tag).siblings('a.Editlink').show();
        $(tag).siblings('a.Savelink').hide();
        $(tag).hide();
    }

    function Save(tag) {
        var tr = $(tag).parents('tr');
        tr.find('#lblEmployeeName').text(tr.find('#txtEmployeeName').val());
        tr.find('#lblPhoneNumber').text(tr.find('#txtPhoneNumber').val());
        tr.find('#lblDepartment').text(tr.find('#DepartmentId :selected').text());
        tr.find('#hdnDeptId').val(tr.find('#DepartmentId').val());
        tr.find('.edit-mode').show();
        tr.find('.display-mode').hide();
        $(tag).siblings('a.Editlink').show();
        $(tag).siblings('a.Cancellink').hide();
        $(tag).hide();

        var EmployeeId = tr.find("#hdnEmpId").val();
        var EmployeeName = tr.find("#lblEmployeeName").text();
        var PhoneNumber = tr.find("#lblPhoneNumber").text();
        var DeptId = tr.find("#hdnDeptId").val();

        var Model =
           {
               "EmployeeId": EmployeeId,
               "EmployeeName": EmployeeName,
               "PhoneNumber": PhoneNumber,
               "DeptId": DeptId
           };
        console.log(Model);
        $.ajax({
            url: '/Employee/save/',
            data: JSON.stringify(Model),
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                alert(data);
                Refreshgrid();
            }
        });
    }

    function Refreshgrid() {
        $.ajax({
            url: '/Employee/GridView/',
            type: 'POST',
            dataType: 'html',
            //contentType: 'application/json; charset=utf-8',
            success: function (data) {
                $("#divgrid").html(data);
            }
        });
    }
</script>

Tuesday, 19 August 2014

MVC ViewModel Pattern

View Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DataAccessLayer.Models;

namespace DataAccessLayer.ViewModels
{
    public class EmployeeViewModel
    {
        public long Emp_Id { get; set; }
        public string Emp_Name { get; set; }
        public Nullable<long> DepartmentId { get; set; }
        public string DepartMentName { get; set; }

        public EmployeeViewModel()
        {
       
        }

        public EmployeeViewModel ConvertToViewModel(Employee emp)
        {
            EmployeeViewModel empvm = new EmployeeViewModel();
            empvm.Emp_Id = emp.Emp_Id;
            empvm.Emp_Name = emp.Emp_Name;
            empvm.DepartmentId = emp.DepartmentId;
            empvm.DepartMentName = emp.Department.DepartmentName;
            return empvm;
        }

        public Employee ConvertToModel(EmployeeViewModel empvm)
        {
            Employee emp = new Employee();
            emp.Emp_Id = empvm.Emp_Id;
            emp.Emp_Name = empvm.Emp_Name;
            emp.DepartmentId = empvm.DepartmentId;
            return emp;
        }

        public List<EmployeeViewModel> ConvertToList(List<Employee> EmpList)
        {
            List<EmployeeViewModel> emplist = new List<EmployeeViewModel>();
            foreach (Employee emp in EmpList)
            {
                EmployeeViewModel Emprec = ConvertToViewModel(emp);
                emplist.Add(Emprec);
            }
            return emplist;
        }
    }
}

Repository

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DataAccessLayer.Models;
using DataAccessLayer.ViewModels;

namespace Repository
{
    public class EmployeeRepository
    {
        DBEntities _dbconn = new DBEntities();

        public IEnumerable<EmployeeViewModel> GetAllEmployee()
        {
            EmployeeViewModel empvm = new EmployeeViewModel();
            return (empvm.ConvertToList(_dbconn.Employees.ToList()));
        }
    }
}

Controller 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Repository;

namespace MvcApplication1.Controllers
{
    public class EmployeeController : Controller
    {
        //
        // GET: /Employee/

        public ActionResult Index()
        {
            EmployeeRepository emprepo = new EmployeeRepository();
            return View(emprepo.GetAllEmployee());
        }
    }
}

Tuesday, 5 August 2014

user repository

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Gammers.Repository;
using Gammers.Models;
using PagedList;
using System.Data;
using System.Data.Common;
using Gammers.Models;
using System.Data.SqlClient;
using System.Configuration;
using Gammers.Helpers;
using System.Threading;
using Gammers.PushNotification;

namespace Gammers.Repository
{
    public class UserRepository
    {
        #region "Declaration"

        private static DBHelper objDBHelper = new DBHelper();
        private string SPName = "SP_UserMaster";
        private string key = "Users";

        #endregion

        #region "Add Parameter"
        private void AddParameter(Pro_UserMaster objPro_UserMaster)
        {
            objDBHelper.Command.Parameters.Clear();
            objDBHelper.AddParameter("@Mode", objPro_UserMaster.Mode);
            objDBHelper.AddParameter("@UserId", objPro_UserMaster.UserId, DbType.Int32);
            objDBHelper.AddParameter("@ContactNo", objPro_UserMaster.ContactNo);
            objDBHelper.AddParameter("@UserName", objPro_UserMaster.UserName);
            objDBHelper.AddParameter("@EmailId", objPro_UserMaster.EmailId);
            objDBHelper.AddParameter("@Sex", objPro_UserMaster.Sex);
            objDBHelper.AddParameter("@Status", objPro_UserMaster.Status);
            objDBHelper.AddParameter("@Birthdate", objPro_UserMaster.Birthdate);
            objDBHelper.AddParameter("@AboutYou", objPro_UserMaster.AboutYou);
            objDBHelper.AddParameter("@Intrestes", objPro_UserMaster.Intrestes);
            objDBHelper.AddParameter("@Hobbies", objPro_UserMaster.Hobbies);
            objDBHelper.AddParameter("@Favoritemovies", objPro_UserMaster.Favoritemovies);
            objDBHelper.AddParameter("@LookingFor", objPro_UserMaster.LookingFor);
            objDBHelper.AddParameter("@ProfilePic", objPro_UserMaster.ProfilePic);
            objDBHelper.AddParameter("@CreatedOn", objPro_UserMaster.CreatedOn);
            objDBHelper.AddParameter("@DeviceId", objPro_UserMaster.DeviceId);
            objDBHelper.AddParameter("@DeviceType", objPro_UserMaster.DeviceType);

            objDBHelper.AddParameter("@MultiIDs", objPro_UserMaster.MultiIDs);
            objDBHelper.AddParameter("@SortBy", objPro_UserMaster.SortBy);
            objDBHelper.AddParameter("@SortOrder", objPro_UserMaster.SortOrder);
            objDBHelper.AddParameter("@SearchField", objPro_UserMaster.SearchField);
            objDBHelper.AddParameter("@SearchValue", objPro_UserMaster.SearchValue);
            objDBHelper.AddParameter("@Name", objPro_UserMaster.Name);
            objDBHelper.AddParameter("@IsActive", objPro_UserMaster.IsActive);
            objDBHelper.AddParameter("@CreatedFrom", objPro_UserMaster.CreatedFrom);
            objDBHelper.AddParameter("@CreatedTo", objPro_UserMaster.CreatedTo);
        }
        #endregion

        #region "Functions"
        public IEnumerable<Pro_UserMaster> GetUsers(Pro_UserMaster objPro_UserMaster)
        {
            objDBHelper = new DBHelper();
            List<Pro_UserMaster> obj_Pro_UserMasterList = new List<Pro_UserMaster>();
            try
            {
                AddParameter(objPro_UserMaster);
                using (SqlDataReader SqlReader = (SqlDataReader)objDBHelper.ExecuteReader(SPName, CommandType.StoredProcedure))
                {
                    while (SqlReader.Read())
                    {
                        Pro_UserMaster obj_Pro_UserMaster = new Pro_UserMaster();
                        obj_Pro_UserMaster.UserId = CommanLogic.GetIntValue(SqlReader["UserId"], 0);
                        obj_Pro_UserMaster.UserName = CommanLogic.GetStringValue(SqlReader["UserName"], string.Empty);
                        obj_Pro_UserMaster.ContactNo = CommanLogic.GetStringValue(SqlReader["ContactNo"], string.Empty);
                        obj_Pro_UserMaster.EmailId = CommanLogic.GetStringValue(SqlReader["EmailId"], string.Empty);
                        obj_Pro_UserMaster.Sex = CommanLogic.GetStringValue(SqlReader["Sex"], string.Empty);
                        DateTime date = CommanLogic.GetDateTimeValue(SqlReader["Birthdate"]);
                        obj_Pro_UserMaster.Birthdate1 = string.Format("{0:dd/MM/yyyy}", date);
                        obj_Pro_UserMaster.Birthdate = CommanLogic.GetDateTimeValue(SqlReader["Birthdate"]);
                        obj_Pro_UserMaster.AboutYou = CommanLogic.GetStringValue(SqlReader["AboutYou"]);
                        obj_Pro_UserMaster.Intrestes = CommanLogic.GetStringValue(SqlReader["Intrestes"]);
                        obj_Pro_UserMaster.Hobbies = CommanLogic.GetStringValue(SqlReader["Hobbies"]);
                        obj_Pro_UserMaster.Favoritemovies = CommanLogic.GetStringValue(SqlReader["Favoritemovies"]);
                        obj_Pro_UserMaster.Status = CommanLogic.GetBoolValue(SqlReader["Status"]);
                        obj_Pro_UserMasterList.Add(obj_Pro_UserMaster);
                    }
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            { objDBHelper = null; }

            return obj_Pro_UserMasterList;
        }

        public IEnumerable<Pro_UserMaster> GetUsersByIDs(string ListofUsers)
        {
            objDBHelper = new DBHelper();
            List<Pro_UserMaster> obj_Pro_UserMasterList = new List<Pro_UserMaster>();
            try
            {
                objDBHelper.Command.Parameters.Clear();
                objDBHelper.AddParameter("@Mode", "SelectListofUsers");
                objDBHelper.AddParameter("@MultiIDs", ListofUsers);
                using (SqlDataReader SqlReader = (SqlDataReader)objDBHelper.ExecuteReader(SPName, CommandType.StoredProcedure))
                {
                    while (SqlReader.Read())
                    {
                        Pro_UserMaster obj_Pro_UserMaster = new Pro_UserMaster();
                        obj_Pro_UserMaster.UserId = CommanLogic.GetIntValue(SqlReader["UserId"], 0);
                        obj_Pro_UserMaster.UserName = CommanLogic.GetStringValue(SqlReader["UserName"], string.Empty);
                        obj_Pro_UserMaster.ContactNo = CommanLogic.GetStringValue(SqlReader["ContactNo"], string.Empty);
                        obj_Pro_UserMaster.EmailId = CommanLogic.GetStringValue(SqlReader["EmailId"], string.Empty);
                        obj_Pro_UserMaster.Sex = CommanLogic.GetStringValue(SqlReader["Sex"], string.Empty);
                        DateTime date = CommanLogic.GetDateTimeValue(SqlReader["Birthdate"]);
                        obj_Pro_UserMaster.Birthdate1 = string.Format("{0:dd/MM/yyyy}", date);
                        obj_Pro_UserMaster.Birthdate = CommanLogic.GetDateTimeValue(SqlReader["Birthdate"]);
                        obj_Pro_UserMaster.AboutYou = CommanLogic.GetStringValue(SqlReader["AboutYou"]);
                        obj_Pro_UserMaster.Intrestes = CommanLogic.GetStringValue(SqlReader["Intrestes"]);
                        obj_Pro_UserMaster.Hobbies = CommanLogic.GetStringValue(SqlReader["Hobbies"]);
                        obj_Pro_UserMaster.Favoritemovies = CommanLogic.GetStringValue(SqlReader["Favoritemovies"]);
                        obj_Pro_UserMaster.Status = CommanLogic.GetBoolValue(SqlReader["Status"]);
                        obj_Pro_UserMasterList.Add(obj_Pro_UserMaster);
                    }
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            { objDBHelper = null; }

            return obj_Pro_UserMasterList;
        }

        public object GetUserCount()
        {
            objDBHelper = new DBHelper();
            try
            {
                objDBHelper.AddParameter("@Mode", "GetUserCount");
                return (objDBHelper.ExecuteScaler(SPName, CommandType.StoredProcedure));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                CacheHelper.Clear(key);
                objDBHelper = null;
            }
        }

        public object SaveUser(Pro_UserMaster user)
        {
            objDBHelper = new DBHelper();
            try
            {
                if (user.UserId > 0)
                    user.Mode = "UPDATE";
                else
                    user.Mode = "INSERT";

                AddParameter(user);
                return objDBHelper.ExecuteScaler(SPName, CommandType.StoredProcedure);

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                CacheHelper.Clear(key);
                objDBHelper = null;
            }
        }

db helper class

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.IO;

namespace Gammers.Models
{
    public class DBHelper
    {
        #region "Private Members"

        private string _ConnString;
        private DbConnection _Connection;
        private DbCommand _Command;
        private DbProviderFactory _Factory = null;

        #endregion

        #region "Cunstructor"
        ///<summary>
        /// Cunstructor
        ///</summary>      
        public DBHelper()
        {
            this._ConnString = string.Empty;
            this.CreateConnection();
        }
        #endregion

        #region "Properties"

        /// <summary>
        /// Gets or Sets the Connection string for the database
        /// </summary>
        public string ConnString
        {
            get { return _ConnString; }
            set
            {
                if (value != string.Empty)
                {
                    _ConnString = value;
                }
            }
        }

        /// <summary>
        /// Gets the Connection object for the database
        /// </summary>
        public DbConnection Connection
        {
            get { return _Connection; }
        }

        /// <summary>
        /// Gets the Command object for the database
        /// </summary>
        public DbCommand Command
        {
            get { return _Command; }
        }

        #endregion

        # region "Methods"

        public void CreateConnection()
        {
            CreateDBObjects(ConfigurationManager.ConnectionStrings["ConnString"].ToString(),
                ConfigurationManager.ConnectionStrings["ConnString"].ProviderName);
        }

        /// <summary>
        /// Determines the correct provider to use and sets up the Connection and Command
        /// objects for use in other methods
        /// </summary>
        /// <param name="connectString">The full Connection string to the database</param>
        /// <param name="providerlist">The enum value of providers from dbutilities.Providers</param>
        public void CreateDBObjects(string connectString, string strProvider)
        {
            _Factory = DbProviderFactories.GetFactory(strProvider);
            _Connection = _Factory.CreateConnection();
            _Command = _Factory.CreateCommand();

            _Connection.ConnectionString = connectString;
            _Command.Connection = Connection;
        }

        #region "Parameters"

        /// <summary>
        /// Creates a parameter and adds it to the Command object
        /// </summary>
        /// <param name="name">The parameter name</param>
        /// <param name="value">The paremeter value</param>
        /// <returns></returns>
        public int AddParameter(string name, object value)
        {
            DbParameter parm = _Factory.CreateParameter();
            parm.ParameterName = name;
            parm.Value = value;
            return Command.Parameters.Add(parm);
        }

        /// <summary>
        /// Creates a parameter and adds it to the Command object
        /// </summary>
        /// <param name="parameter">A parameter object</param>      
        public int AddParameter(DbParameter parameter)
        {
            return Command.Parameters.Add(parameter);
        }

        /// <summary>
        /// Creates a parameter and adds it to the Command object
        /// </summary>
        /// <param name="name">A parameter Name</param>
        /// <param name="Value">A parameter Value</param>
        /// <param name="dbType">A parameter data type</param>
        public int AddParameter(string name, object value, DbType dbtype)
        {
            DbParameter parm = _Factory.CreateParameter();
            parm.ParameterName = name;
            parm.Value = value;
            parm.DbType = dbtype;
            return Command.Parameters.Add(parm);
        }

        /// <summary>
        /// Creates a parameter and adds it to the Command object
        /// </summary>
        /// <param name="name">A parameter Name</param>
        /// <param name="Value">A parameter Value</param>
        /// <param name="dbType">A parameter data type</param>
        /// <param name="size">A prameter size in int</param>
        public int AddParameter(string name, object value, DbType dbtype, int size)
        {
            DbParameter parm = _Factory.CreateParameter();
            parm.ParameterName = name;
            parm.Value = value;
            parm.DbType = dbtype;
            parm.Size = size;
            return Command.Parameters.Add(parm);
        }

        /// <summary>
        /// Creates a parameter and adds it to the Command object
        /// </summary>
        /// <param name="name">A parameter Name</param>
        /// <param name="Value">A parameter Value</param>
        /// <param name="dbType">A parameter data type</param>
        /// <param name="Direction">A prameter Direction</param>
        public int AddParameter(string name, object value, DbType dbtype, ParameterDirection direction)
        {
            DbParameter parm = _Factory.CreateParameter();
            parm.ParameterName = name;
            parm.Value = value;
            parm.DbType = dbtype;
            parm.Direction = direction;
            return Command.Parameters.Add(parm);
        }

        /// <summary>
        /// Creates a parameter and adds it to the Command object
        /// </summary>
        /// <param name="name">A parameter Name</param>
        /// <param name="Value">A parameter Value</param>
        /// <param name="dbType">A parameter data type</param>
        /// <param name="size">A prameter size in int</param>
        /// <param name="Direction">A prameter Direction</param>
        public int AddParameter(string name, object value, DbType dbtype, int size, ParameterDirection direction)
        {
            DbParameter parm = _Factory.CreateParameter();
            parm.ParameterName = name;
            parm.Value = value;
            parm.DbType = dbtype;
            parm.Size = size;
            parm.Direction = direction;
            return Command.Parameters.Add(parm);
        }

        #endregion

        #region "DB Transactions"

        /// <summary>
        /// Starts a transaction for the Command object
        /// </summary>
        private void BeginTransaction()
        {
            if (Connection.State.Equals(ConnectionState.Closed))
            {
                Connection.Open();
            }
            Command.Transaction = Connection.BeginTransaction();
        }

        /// <summary>
        /// Commits a transaction for the Command object
        /// </summary>
        private void CommitTransaction()
        {
            Command.Transaction.Commit();
            Connection.Close();
        }

        /// <summary>
        /// Rolls back the transaction for the Command object
        /// </summary>
        private void RollbackTransaction()
        {
            Command.Transaction.Rollback();
            Connection.Close();
        }

        #endregion

        #region "Execute DB Functions"

        /// <summary>
        /// Executes a statement that does not return a result set, such as an INSERT, UPDATE, DELETE, or a data definition statement
        /// </summary>
        /// <param name="query">The query, either SQL or Procedures</param>
        /// <param name="Commandtype">The Command type, text, storedprocedure, or tabledirect</param>
        /// <param name="Connectionstate">The Connection state</param>
        /// <returns>An integer value</returns>
        public int ExecuteNonQuery(string commandText, CommandType commandType)
        {
            Command.CommandText = commandText;
            Command.CommandType = commandType;
            int i = -1;

            try
            {
                if (Connection.State.Equals(ConnectionState.Closed))
                {
                    Connection.Open();
                }

                //BeginTransaction();

                i = Command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                //RollbackTransaction();
                throw (ex);
            }
            finally
            {
                //CommitTransaction();
                Command.Parameters.Clear();

                if (Connection.State.Equals(ConnectionState.Open))
                {
                    Connection.Close();
                    Connection.Dispose();
                }
            }

            return i;
        }

        /// <summary>
        /// Executes a statement that returns a single value.
        /// If this method is called on a query that returns multiple rows and columns, only the first column of the first row is returned.
        /// </summary>
        /// <param name="query">The query, either SQL or Procedures</param>
        /// <param name="Commandtype">The Command type, text, storedprocedure, or tabledirect</param>
        /// <param name="Connectionstate">The Connection state</param>
        /// <returns>An object that holds the return value(s) from the query</returns>
        public object ExecuteScaler(string commandText, CommandType commandType)
        {
            Command.CommandText = commandText;
            Command.CommandType = commandType;
            object obj = null;
            try
            {
                if (Connection.State.Equals(ConnectionState.Closed))
                {
                    Connection.Open();
                }

                BeginTransaction();
                obj = Command.ExecuteScalar();
            }
            catch (Exception ex)
            {
                RollbackTransaction();
                throw (ex);
            }
            finally
            {
                CommitTransaction();
                Command.Parameters.Clear();

                if (Connection.State.Equals(ConnectionState.Open))
                {
                    Connection.Close();
                    Connection.Dispose();
                    Command.Dispose();
                }
            }

            return obj;
        }

        /// <summary>
        /// Executes a SQL statement that returns a result set.
        /// </summary>
        /// <param name="query">The query, either SQL or Procedures</param>
        /// <param name="Commandtype">The Command type, text, storedprocedure, or tabledirect</param>
        /// <param name="Connectionstate">The Connection state</param>
        /// <returns>A datareader object</returns>
        public DbDataReader ExecuteReader(string query, CommandType Commandtype)
        {
            //this.CreateConnection();
            Command.CommandText = query;
            Command.CommandType = Commandtype;
            DbDataReader reader = null;
            try
            {
                if (Connection.State.Equals(ConnectionState.Closed))
                {
                    Connection.Open();
                }
                reader = Command.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            finally
            {
                Command.Parameters.Clear();
            }

            return reader;
        }

        /// <summary>
        /// Generates a dataset
        /// </summary>
        /// <param name="query">The query, either SQL or Procedures</param>
        /// <param name="Commandtype">The Command type, text, storedprocedure, or tabledirect</param>
        /// <param name="Connectionstate">The Connection state</param>
        /// <returns>A dataset containing data from the database</returns>
        public DataSet GetDataSet(string query, CommandType Commandtype)
        {
            DbDataAdapter adapter = _Factory.CreateDataAdapter();
            Command.CommandText = query;
            Command.CommandType = Commandtype;
            adapter.SelectCommand = Command;
            DataSet ds = new DataSet();
            try
            {
                adapter.Fill(ds);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Command.Parameters.Clear();

                if (Connection.State.Equals(ConnectionState.Open))
                {
                    Connection.Close();
                    Connection.Dispose();
                    Command.Dispose();
                }
            }
            return ds;
        }

        /// <summary>
        /// Generates a dataset
        /// </summary>
        /// <param name="query">The query, either SQL or Procedures</param>
        /// <param name="Commandtype">The Command type, text, storedprocedure, or tabledirect</param>
        /// <param name="Connectionstate">The Connection state</param>
        /// <returns>A dataset containing data from the database</returns>
        public DataSet GetDataSet(string query, CommandType Commandtype, string tableName)
        {
            DbDataAdapter adapter = _Factory.CreateDataAdapter();
            Command.CommandText = query;
            Command.CommandType = Commandtype;
            adapter.SelectCommand = Command;
            DataSet ds = new DataSet();
            try
            {
                adapter.Fill(ds, tableName);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Command.Parameters.Clear();

                if (Connection.State.Equals(ConnectionState.Open))
                {
                    Connection.Close();
                    Connection.Dispose();
                    Command.Dispose();
                }
            }
            return ds;
        }

        #endregion

        #endregion
    }
}

My Sql connectivity

mysql commandprompt

Step1 : Open CMD
Step2 : Paste the command --> cd "Program Files\MySQL\MySQL Server 5.6\bin\"
Step3 : Type --> mysql.exe
Step4 : Create database test
etc...

connectivity :

in helper class

public static string GetConnectionString()
{
            string connStr = "server=localhost;Database=test;Uid=root;pwd=;";
            return connStr;
}

private void LoadData()
{
        string strconn = Helper.GetConnectionString();
        MySqlConnection _dbconn = new MySqlConnection(strconn);
        _dbconn.Open();
        try
        {
            MySqlCommand cmd = _dbconn.CreateCommand();
            cmd.CommandText = "select * from employee";
            MySqlDataAdapter adap =new MySqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adap.Fill(ds);
            GridView1.DataSource = ds.Tables[0].DefaultView;
            GridView1.DataBind();
        }
        catch(Exception)
        {}
        finally
        {
            if(_dbconn.State == ConnectionState.Open)
            {
                _dbconn.Close();
            }
        }   
}

Monday, 31 March 2014

controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Gammers.Models;
using Gammers.Repository;
using Gammers.Helpers;
using System.Web.Optimization;
using System.Threading.Tasks;
using System.Web;
using System.IO;
using System.Drawing;
using System.ComponentModel;
using System.Web.Hosting;
using System.Drawing.Imaging;
using System.Net.Http.Headers;
using System.Diagnostics;
using HoiioSDK.NET;
using Newtonsoft.Json;
using System.Windows.Forms;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web.Script.Serialization;
using System.Configuration;
using System.Globalization;
using System.Data;

namespace Controllers
{
    public class UserController : ApiController
    {

        [HttpPost]
        [ActionName("AuthenticateUser")]
        public dynamic AuthenticateUser(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();

            var Result = Convert.ToInt32(new UserRepository().AuthentucateUser(user.EmailId, user.ContactNo));
            if (Result == -1)
                dicto = ServiceHelper.GetServiceJson(ServiceHelper.JsonType.Error, StatusConstants.Error, null, "Email does not exists."); // msg as per client said
            else if (Result == -2)
                dicto = ServiceHelper.GetServiceJson(ServiceHelper.JsonType.Error, StatusConstants.Error, null, "Contact does not exists."); //msg as per client said
            else
            {
                Random rnd = new Random();
                string code = rnd.Next(1000, 10000).ToString();
                if (code.Length == 3)
                    code = code + "0";
                else if (code.Length == 2)
                    code = code + "00";
                dicto = new Dictionary<string, dynamic>();


                //-------------------Send Email with varfication code--------------
                bool EmailStatus = EmailHelper.SendEmailForVarificationCode(user.EmailId, code, user.ContactNo);
                if (EmailStatus == true)
                {
                    dicto.Add("code", code);
                    dicto.Add("Result", "Email Send Successfully");
                }
                else
                    dicto.Add("Result", "Email Sending fail");
                //-------------------End-------------------------------------------
            }
            return dicto;
        }

        private int GetTempId(string emailid)
        {
            if (emailid == Convert.ToString("abc@gmail.com").ToLower())
                return 1;
            else if (emailid == Convert.ToString("xyz@gmail.com").ToLower())
                return 2;
            else if (emailid == Convert.ToString("Gee@gmail.com").ToLower())
                return 3;
            else if (emailid == Convert.ToString("dip@gmail.com").ToLower())
                return 4;
            else if (emailid == Convert.ToString("mj@gmail.com").ToLower())
                return 5;
            else if (emailid == Convert.ToString("roj@gmail.com").ToLower())
                return 6;
            else
                return 0;
        }

        [HttpPost]
        [ActionName("RegisterUser")]
        public dynamic RegisterUser(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            user.DeviceId = user.DeviceId.Replace(" ","");
            Pro_UserDetail Userdetail = new UserRepository().InsertUser(user);
            if (Userdetail.UserId > 0)
            {
                dicto.Add("Message", Userdetail.Message);
                dicto.Add("UserId", Userdetail.UserId);
                dicto.Add("CreatedOn", Userdetail.CreatedOn);
            }
            else
            {
                dicto.Add("Message", Userdetail.Message);
                dicto.Add("UserId", Userdetail.UserId);
                dicto.Add("CreatedOn", Userdetail.CreatedOn);
            }
         
            return dicto;
        }

        [HttpPost]
        [ActionName("RefreshContacts")]
        public dynamic RefreshContacts(Pro_ContactDetails user)
        {
            int i = 0;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            i = Convert.ToInt32(new ContactDetailsRepository().UpdateIsFriend(user.UserId, user.CreatedOn));

            if (i == 1)
            {
                var ContactDetails = new ContactDetailsRepository().GetFriendList(user.UserId, user.CreatedOn);
                if (ContactDetails.Count > 0)
                    dicto.Add("Result", ContactDetails);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("InsertContactDetails")]
        public dynamic InsertContactDetails(Pro_ContactDetails user)
        {
            string contacts = string.Empty;
            int i = 0;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            contacts = Convert.ToString(user.ContactArray);
            JavaScriptSerializer jss = new JavaScriptSerializer();
            List<Pro_ContactDetails_Api> Contactlist = jss.Deserialize<List<Pro_ContactDetails_Api>>(contacts);
            string result = new ContactDetailsRepository().InsertContacts(Contactlist, user.UserId, user.CreatedOn);
            if (result == "Success")
            {
                i = Convert.ToInt32(new ContactDetailsRepository().UpdateIsFriend(user.UserId, user.CreatedOn));
            }
            if (i == 1)
            {
                var ContactDetails = new ContactDetailsRepository().GetFriendList(user.UserId, user.CreatedOn);
                if (ContactDetails != null)
                    dicto.Add("Result", ContactDetails);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("RestoreFriendList")]
        public dynamic RestoreFriendList(Pro_FriendsContactDetails_Api user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserDetails = new ContactDetailsRepository().RestoreFriendList(Convert.ToInt32(user.UserId));
            if (UserDetails.Count > 0)
                dicto.Add("Result", UserDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetFeaturedMember")]
        public dynamic GetFeaturedMember(Pro_UserMaster_Api user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserDetails = new UserRepository().GetFeaturedMember(user.UserId);
            if (UserDetails.UserId > 0)
                dicto.Add("Result", UserDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetHighlightedPicture")]
        public dynamic GetHighlightedPicture(Pro_PictureShareMaster_Api Picture)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var PictureDetails = new PictureShareRepository().GetTotalSharePicture(Picture.UserId);
            if (PictureDetails.Count > 0)
                dicto.Add("Result", PictureDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetHighlightedVideos")]
        public dynamic GetHighlightedVideos(Pro_VideoShareMaster_Api Video)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var VideoDetails = new VideoShareRepository().GetTotalShareVideos(Video.UserId);
            if (VideoDetails.Count > 0)
                dicto.Add("Result", VideoDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetUserContactDetails")]
        public dynamic GetUserContactDetails(Pro_UserContact user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var UserContactDetails = new UserContactRepository().GetUserContactDetails(user.UserId, user.Flag);
            if (UserContactDetails.Count > 0)
                dicto.Add("Result", UserContactDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetUserProfile")]
        public dynamic GetUserProfile(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserProfile = new UserRepository().GetUserProfile(user.UserId);

            if (UserProfile.UserId > 0)
                dicto.Add("Result",UserProfile);
            else
                dicto.Add("Status",Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("UpdateProfileAndProfilePic")]
        public System.Threading.Tasks.Task<Dictionary<string, dynamic>> UpdateProfileAndProfilePic()
        {
            HttpRequestMessage request = Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            var user = new Pro_UserMaster();
            bool Status = false;
            var root = HttpContext.Current.Server.MapPath("~/Uploads/ProfilePicture");
            var provider = new MultipartFormDataStreamProvider(root);

            var task = request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(o =>
                {
                    foreach (var key in provider.FormData.AllKeys)
                    {
                        var values = provider.FormData.GetValues(key);
                        if (values != null)
                            foreach (var val in values)
                            {
                                if (string.Equals(key, "UserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.UserId = Convert.ToInt32(val);
                                }
                                if (string.Equals(key, "UserName", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.UserName = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Sex", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Sex = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Birthdate", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Birthdate = Convert.ToDateTime(val);
                                }
                                else if (string.Equals(key, "AboutYou", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.AboutYou = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Intrestes", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Intrestes = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Hobbies", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Hobbies = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Favoritemovies", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Favoritemovies = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "LookingFor", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.LookingFor = Convert.ToString(val);
                                }
                                break;
                            }
                    }

                    if (user.UserId > 0)
                    {
                        if (provider.FileData.Count != 0)
                        {
                            string OldPic = new UserRepository().GetProfilePic(user.UserId);
                            if (!string.IsNullOrEmpty(OldPic))
                            {
                                if (File.Exists(root + "/" + OldPic))
                                {
                                    File.Delete(root + "/" + OldPic);
                                    File.Delete(root + "/" + "Thumb_" + OldPic);
                                }
                            }
                            //var ProfilePic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + user.UserId + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                            //var ProfilePic = "ProfilePic_" + user.UserId + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                            var ProfilePic = "ProfilePic_" + user.UserId + ".png";
                            var finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                            var img = System.Drawing.Image.FromFile(finfo.FullName);
                            //img = Helpers.ImageExtensions.Resize(img, Width, Height);
                            var converter = new System.Drawing.ImageConverter();
                            var b = (byte[])converter.ConvertTo(img, typeof(byte[]));
                            user.ProfilePic = ProfilePic;
                            user.Mode = "UpdateProfilePic";
                            int retval = Convert.ToInt32(new UserRepository().SaveProfile(user));
                            Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, ProfilePic), img.Width, img.Height);
                            Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, "Thumb_" + ProfilePic), 100, 100);
                            img.Dispose();
                            Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                            //System.IO.File.Move(finfo.FullName, System.IO.Path.Combine(root, userImage));
                            if (retval == 0)
                            {
                                if (File.Exists(root + "/" + ProfilePic))
                                {
                                    File.Delete(root + "/" + ProfilePic);
                                    File.Delete(root + "/" + "Thumb_" + ProfilePic);
                                }
                                Status =Convert.ToBoolean(0);
                            }
                        }

                        user.Mode = "UpdateProfile";
                        int Returnval = Convert.ToInt32(new UserRepository().SaveProfile(user));
                        if (Returnval > 0)
                            Status = Convert.ToBoolean(1);
                        else
                            Status = Convert.ToBoolean(0);

                    }
                    Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
                    dicto.Add("Status", Status);
                    return dicto;
                   // return ServiceHelper.GetServiceJson(ServiceHelper.JsonType.ResultMessage, StatusConstants.Ok, Status);
                }
            );
            return task;
        }

        public dynamic GetVideo(int id)
        {
            Pro_VideoMaster objpicture = new Pro_VideoMaster();
            objpicture = new VideoRepository().GetVideoById(id);
            byte[] Content = objpicture.VideoContent;
            //MemoryStream ms = new MemoryStream(Content);

            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream(Content);
            object rval = formatter.Deserialize(stream);
            stream.Close();
            return rval;
        }

        //public HttpResponseMessage Get(int id)
        //{
        //    Pro_PictureMaster objpicture = new Pro_PictureMaster();
        //    objpicture = new PictureRepository().GetPictureById(id);
        //    byte[] imgData = objpicture.ImageContent;
        //    MemoryStream ms = new MemoryStream(imgData);
        //    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
        //    response.Content = new StreamContent(ms);
        //    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");

        //    return response;
        //}
        [HttpPost]
        [ActionName("InsertChat")]
        public dynamic InsertChat(Pro_ChatHistoryMaster chatHistory)
        {
            Dictionary<string, dynamic> dicto;
            if (chatHistory.GroupId != 0)
            {
                Pro_GroupChatDateDetail chat = new ChatHistoryRepository().InsertGroupChat(chatHistory);
                dicto = new Dictionary<string, dynamic>();
                if (chat.Status == true)
                {
                    //dicto.Add("ChatId", ChatId);
                    dicto.Add("Result", chat);
                }
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            else
            {
                Pro_ChatDateDetail Chat = new ChatHistoryRepository().SaveChat(chatHistory);
                dicto = new Dictionary<string, dynamic>();
                if (Chat.ServerID > 0)
                {
                    dicto.Add("Result", Chat);
                    //dicto.Add("Status", Convert.ToBoolean(1));
                }
                else
                {
                    dicto.Add("Status", Convert.ToBoolean(0));
                }
            }

            return dicto;

        }

        [HttpPost]
        [ActionName("InsertChatwithImageOrVideo")]
        public System.Threading.Tasks.Task<Dictionary<string, dynamic>> InsertChatwithImageOrVideo()
        {
            HttpRequestMessage request = Request;
            Pro_GroupChatDateDetail chatdetail = new Pro_GroupChatDateDetail();
            Pro_ChatDateDetail Chat = new Pro_ChatDateDetail();
            int Height = 0;
            int Width = 0;
            string Upload = string.Empty;
            string FileName = string.Empty;
            byte[] buffer = null;
            long offset = 0;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            var chathistory = new Pro_ChatHistoryMaster();
            string strmsg = string.Empty;
            //var root =Helpers.ConstantValues.RootUrl;
            var root = HttpContext.Current.Server.MapPath("~/Uploads/ChatHistory");
            var provider = new MultipartFormDataStreamProvider(root);
            Dictionary<string, dynamic> dicto = null;
            var task = request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(o =>
                {
                    foreach (var key in provider.FormData.AllKeys)
                    {
                        var values = provider.FormData.GetValues(key);
                        if (values != null)
                            foreach (var val in values)
                            {
                                if (string.Equals(key, "FromId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        chathistory.FromId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "ToId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        chathistory.ToId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "GroupId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        chathistory.GroupId = Convert.ToInt32(val);
                                }
                                //else if (string.Equals(key, "ChatOn", StringComparison.OrdinalIgnoreCase))
                                //{
                                //    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                //        chathistory.ChatOn = Convert.ToDateTime(val);
                                //}
                                else if (string.Equals(key, "Upload", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        Upload = val;
                                }
                                //else if (string.Equals(key, "FileName", StringComparison.OrdinalIgnoreCase))
                                //{
                                //    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                //        FileName = val;
                                //}
                                //else if (string.Equals(key, "buffer", StringComparison.OrdinalIgnoreCase))
                                //{
                                //    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                //        buffer = Encoding.ASCII.GetBytes(val);
                                //}
                                //else if (string.Equals(key, "Offset", StringComparison.OrdinalIgnoreCase))
                                //{
                                //    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                //        offset =  Convert.ToInt64(val);
                                //}
                                break;
                            }
                    }

                    if (Upload == "Image")
                    {
                        var chatId = 0;
                        string msg = string.Empty;

                        //var userImage = Helpers.HelperFunctions.CreateUniqueFileName() + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                        var userImage = Helpers.HelperFunctions.CreateUniqueFileName() + ".png";
                        chathistory.ImagePath = userImage;

                        var finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                        var img = System.Drawing.Image.FromFile(finfo.FullName);
                        //img = Helpers.ImageExtensions.Resize(img, Width, Height);

                        var converter = new System.Drawing.ImageConverter();
                        var b = (byte[])converter.ConvertTo(img, typeof(byte[]));
                        bool retval = Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, userImage), img.Width, img.Height);

                        img.Dispose();
                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                        dicto = new Dictionary<string, dynamic>();
                        if (retval)
                        {
                            Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, "Thumb_" + userImage), 100, 100);
                            if (chathistory.GroupId != 0)
                            {
                                chatdetail = new ChatHistoryRepository().InsertGroupChat(chathistory);
                                if (chatdetail.Status == true)
                                {
                                    dicto.Add("Result", chatdetail);
                                    dicto.Add("Message", "File Uploaded Successfully");
                                }
                                else
                                {
                                    if (File.Exists(root + "/" + userImage))
                                        DeleteImageVideo(root + "/" + userImage);
                                    dicto.Add("Message", msg);
                                }
                            }
                            else
                            {
                                Chat = new ChatHistoryRepository().SaveChat(chathistory);
                                //chatId = Convert.ToInt32(new ChatHistoryRepository().SaveChat(chathistory));
                                if (Chat.ServerID > 0)
                                {
                                    dicto.Add("Result", Chat);
                                    dicto.Add("Message", "File Uploaded Successfully");
                                }
                                else
                                {
                                    if (File.Exists(root + "/" + userImage))
                                    {
                                        DeleteImageVideo(root + "/" + userImage);
                                        DeleteImageVideo(root + "/" + userImage + "_Thumb");
                                    }
                                    dicto.Add("Message", "File Upload fail");
                                }
                            }
                        }
                        else
                        {
                            dicto.Add("Message", "File Uploaded Fail.");
                        }
                    }
                    else
                    {
                        dicto = new Dictionary<string, dynamic>();
                        string msg = string.Empty;
                        var UserVideo = Helpers.HelperFunctions.CreateUniqueFileName() + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                        chathistory.VideoPath = UserVideo;

                        var finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                        System.IO.File.Move(finfo.FullName, System.IO.Path.Combine(root, UserVideo));
                        if (File.Exists(root + "/" + UserVideo))
                        {
                            if (chathistory.GroupId != 0)
                            {
                                chatdetail = new ChatHistoryRepository().InsertGroupChat(chathistory);
                                if (chatdetail.Status == true)
                                {
                                    dicto.Add("Result", chatdetail);
                                    dicto.Add("Message", "File Uploaded Successfully");
                                }
                                else
                                {
                                    if (File.Exists(root + "/" + UserVideo))
                                        DeleteImageVideo(root + "/" + UserVideo);
                                    dicto.Add("Message", msg);
                                }
                            }
                            else
                            {
                                Chat = new ChatHistoryRepository().SaveChat(chathistory);
                                //chatId = Convert.ToInt32(new ChatHistoryRepository().SaveChat(chathistory));
                                if (Chat.ServerID > 0)
                                {
                                    dicto.Add("Result", Chat);
                                    dicto.Add("Message", "File Uploaded Successfully");
                                }
                                else
                                {
                                    if (File.Exists(root + "/" + UserVideo))
                                        DeleteImageVideo(root + "/" + UserVideo);
                                    dicto.Add("Message", "File Upload fail");
                                }
                            }
                        }

                    }

                    return dicto;
                    //return ServiceHelper.GetServiceJson(ServiceHelper.JsonType.ResultMessage, StatusConstants.Ok, strmsg);
                }
            );
            return task;
        }

        public void DeleteImageVideo(string FilePath)
        {
            File.Delete(FilePath);
        }

        [HttpPost]
        [ActionName("GetMyNewMsg")]
        public dynamic GetMyNewMsg(Pro_ChatHistoryMaster Chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            List<Pro_ChatHistoryDetail> chats = new ChatHistoryRepository().GetMyNewMsg(Chat.FromId, Chat.ToId, Chat.ChatDate);
            Pro_Status Status = new UserRepository().GetUserStatus(Chat.FromId,Chat.ChatId);

            if (chats.Count > 0)
            {
                dicto.Add("Result", chats);
                dicto.Add("IsOnline", Status.IsOnline);
                dicto.Add("IsTyping", Status.IsTyping);
            }
            else
            {
                dicto.Add("IsOnline", Status.IsOnline);
                dicto.Add("IsTyping", Status.IsTyping);
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("GetGroupChatHistory")]
        public dynamic GetGroupChatHistory(Pro_ChatHistoryMaster Chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            List<Pro_GroupChatHistoryDetail> chats = new ChatHistoryRepository().GetGroupChatHistory(Chat.ToId, Chat.GroupId);
            if (chats.Count > 0)
                dicto.Add("Result", chats);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetMyNewGroupMsg")]
        public dynamic GetMyNewGroupMsg(Pro_ChatHistoryMaster Chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            List<Pro_GroupChatHistoryDetail> chats = new ChatHistoryRepository().GetMyNewGroupMsg(Chat.ToId, Chat.GroupId, Chat.ChatDate);
            if (chats.Count > 0)
                dicto.Add("Result", chats);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("InsertGroup")]
        public dynamic InsertGroup(Pro_GroupMaster chatHistory)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            if (chatHistory.ListofUsers != null)
            {
                chatHistory.CreatedOn = DateTime.UtcNow;
                int GroupId = Convert.ToInt32(new GroupRepository().SaveGroup(chatHistory));
                if (GroupId > 0)
                    dicto.Add("GroupId", GroupId);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetAllGroupsByUserId")]
        public dynamic GetAllGroupsByUserId(int UserId)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserGroups = new GroupRepository().GetAllGroupsByUserId(UserId);
            if (UserGroups != null)
               dicto.Add("Result", UserGroups);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetGroupsByGroupId")]
        public dynamic GetGroupsByGroupId(int GroupId)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var groupsDetail = new GroupRepository().GetGroupsByGroupId(GroupId);

            if (groupsDetail != null)
                dicto.Add("Result", groupsDetail);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("GetAllGroupUser")]
        public dynamic GetAllGroupUser(Pro_GroupMaster chatHistory)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var groupsDetail = new GroupRepository().GetAllGroupUser(chatHistory.GroupId);

            if (groupsDetail != null)
               dicto.Add("Result", groupsDetail);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        #region Webposter current

        [HttpPost]
        [ActionName("AddToWebPoster1")]
        public dynamic AddToWebPoster1(Pro_WebPoster objWebPoster)
        {
            string strmsg = string.Empty;
            bool IsDataRemain;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();

            if (objWebPoster.Share == 0)
            {
                long offset = Convert.ToInt64(objWebPoster.Offset);
                string path = string.Empty;
                if (objWebPoster.FromCommunity == true)
                    path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["CommunityUrl"]);
                else
                    path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["WebPosterUrl"]);

                if (objWebPoster.ContentType == "Image")
                    objWebPoster.ChatImgName = objWebPoster.FileName;
                else
                    objWebPoster.ChatVideoName = objWebPoster.FileName;
                if (objWebPoster.IsUploadingEnd == true)
                {
                    new Helpers.HelperFunctions().UploadFile(objWebPoster.FileName, objWebPoster.buffer, offset, path);
                    IsDataRemain = false;
                }
                else
                {
                    IsDataRemain = new Helpers.HelperFunctions().UploadFile(objWebPoster.FileName, objWebPoster.buffer, offset, path);
                    dicto.Add("Success", IsDataRemain);
                }
                if (IsDataRemain == false)
                {
                    if (objWebPoster.ContentType == "Image")
                    {
                        //--------------Thumb image------------------------------------
                        if (objWebPoster.ContentType == "Image")
                            Helpers.HelperFunctions.SaveThumbImage(path + objWebPoster.FileName, 100, 100, "Thumb_");
                        //--------------End Thumb image--------------------------------


                        int pictureId = Convert.ToInt32(new PictureRepository().SaveUserPicture(objWebPoster.LoginUserId, objWebPoster.ChatImgName, Convert.ToDateTime(objWebPoster.CreatedOn), objWebPoster.FromCommunity));
                        if (pictureId > 0)
                        {
                            if (objWebPoster.FromCommunity == true)
                            {
                                dicto.Add("Status", Convert.ToBoolean(1));
                                dicto.Add("ContentId", pictureId);
                            }
                            else
                                dicto.Add("Status", Convert.ToBoolean(1));
                        }
                        else
                        {
                            if (File.Exists(path + "/" + objWebPoster.FileName))
                            {
                                DeleteImageVideo(path + "/" + objWebPoster.FileName);
                                DeleteImageVideo(path + "/" + "Thumb_" + objWebPoster.FileName);
                            }
                            dicto.Add("Status", Convert.ToBoolean(0));
                        }

                    }
                    else
                    {

                        int VideoId = Convert.ToInt32(new VideoRepository().SaveUserVideo(objWebPoster.LoginUserId, objWebPoster.ChatVideoName, Convert.ToDateTime(objWebPoster.CreatedOn), objWebPoster.FromCommunity));
                        if (VideoId > 0)
                        {
                            if (objWebPoster.FromCommunity == true)
                            {
                                dicto.Add("Status", Convert.ToBoolean(1));
                                dicto.Add("ContentId", VideoId);
                            }
                            else
                                dicto.Add("Status", Convert.ToBoolean(1));
                        }
                        else
                        {
                            if (File.Exists(path + "/" + objWebPoster.FileName))
                            {
                                DeleteImageVideo(path + "/" + objWebPoster.FileName);
                            }
                            dicto.Add("Status", Convert.ToBoolean(0));
                        }
                    }
                }
            }
            else //---If Share
            {
                if (objWebPoster.ContentType == "Image")
                {
                    Pro_PictureShareMaster objPictureShare = new Pro_PictureShareMaster();
                    objPictureShare.UserId = objWebPoster.LoginUserId;
                    objPictureShare.PictureId = objWebPoster.ContentId;
                    objPictureShare.ShareId = objWebPoster.FromUserId;
                    objPictureShare.CreatedOn = objWebPoster.CreatedOn;
                    objPictureShare.FromCommunity = objWebPoster.FromCommunity;
                    int pictureShareId = Convert.ToInt32(new PictureShareRepository().SaveSharePicture(objPictureShare));
                    if (pictureShareId > 0)
                    {
                        dicto.Add("Status", Convert.ToBoolean(1));
                    }
                    else
                    {
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }
                }
                else
                {
                    Pro_VideoShareMaster objVideoShare = new Pro_VideoShareMaster();
                    objVideoShare.UserId = objWebPoster.LoginUserId;
                    objVideoShare.VideoId = objWebPoster.ContentId;
                    objVideoShare.CreatedOn = DateTime.UtcNow.ToString();
                    objVideoShare.ShareId = objWebPoster.FromUserId;
                    objVideoShare.FromCommunity = objWebPoster.FromCommunity;
                    int VideoShareId = Convert.ToInt32(new VideoShareRepository().SaveShareVideo(objVideoShare));
                    if (VideoShareId > 0)
                    {
                        dicto.Add("Status", Convert.ToBoolean(1));
                    }
                    else
                    {
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }
                }
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("AddToWebPoster")]
        public System.Threading.Tasks.Task<Dictionary<string, dynamic>> AddToWebPoster()
        {
            HttpRequestMessage request = Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            var webposter = new Pro_WebPoster();
            string strmsg = string.Empty;
            string ContentType = string.Empty;
            string strChatContent = string.Empty;
            var root = HttpContext.Current.Server.MapPath("~/Uploads/WebPoster");
            var provider = new MultipartFormDataStreamProvider(root);

            Image img = null;
            byte[] b = null;
            System.IO.FileInfo finfo = null;
            var webposterPic = "";
            var webposterVideo = "";

            var task = request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(o =>
                {
                    foreach (var key in provider.FormData.AllKeys)
                    {
                        var values = provider.FormData.GetValues(key);
                        if (values != null)
                            foreach (var val in values)
                            {
                                if (string.Equals(key, "Share", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.Share = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "LoginUserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.LoginUserId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "FromUserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.FromUserId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "ContentType", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        ContentType = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "ContentId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.ContentId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "CreatedOn", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.CreatedOn = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "FromCommuniy", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.FromCommunity = Convert.ToBoolean(val);
                                }
                                break;
                            }
                    }

                    if (webposter.LoginUserId > 0)
                    {
                        if (webposter.Share == 0)
                        {
                            if (provider.FileData.Count != 0)
                            {
                                if (ContentType == "Image")
                                {
                                    //webposterPic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + webposter.LoginUserId + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                                    webposterPic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + webposter.LoginUserId + ".png";
                                    finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                                    img = System.Drawing.Image.FromFile(finfo.FullName);
                                    var converter = new System.Drawing.ImageConverter();
                                    b = (byte[])converter.ConvertTo(img, typeof(byte[]));
                                    webposter.WebposterImg = webposterPic;
                                    DateTime dt = DateTime.UtcNow;
                                    //DateTime dt = Convert.ToDateTime(webposter.CreatedOn);
                                    int pictureId = Convert.ToInt32(new PictureRepository().SaveUserPicture(webposter.LoginUserId, webposterPic, dt, webposter.FromCommunity));

                                    if (pictureId > 0)
                                    {
                                        //----Image upload-----
                                        Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, webposterPic), img.Width, img.Height);
                                        Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, "Thumb_" + webposterPic), 100, 100);
                                        img.Dispose();
                                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                                        strmsg = "1";
                                        //----End Image upload-----
                                    }
                                    else
                                        strmsg = "0";
                                }
                                else if (ContentType == "Video")
                                {
                                    webposterVideo = Helpers.HelperFunctions.CreateUniqueFileName() + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                                    webposter.WebposterVideo = webposterVideo;
                                    DateTime dt = DateTime.UtcNow;
                                    int VideoId = Convert.ToInt32(new VideoRepository().SaveUserVideo(webposter.LoginUserId, webposterVideo, dt, webposter.FromCommunity));
                                    if (VideoId > 0)
                                    {
                                        //----video upload-----
                                        finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                                        System.IO.File.Move(finfo.FullName, System.IO.Path.Combine(root, webposterVideo));
                                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                                        strmsg = "1";
                                        //----End video upload-----
                                    }
                                    else
                                        strmsg = "0";
                                }
                            }
                        }
                        else
                        {
                            if (ContentType == "Image")
                            {
                                Pro_PictureShareMaster objPictureShare = new Pro_PictureShareMaster();
                                objPictureShare.UserId = webposter.LoginUserId;
                                objPictureShare.PictureId = webposter.ContentId;
                                objPictureShare.CreatedOn = DateTime.UtcNow.ToString();
                                objPictureShare.ShareId = webposter.FromUserId;
                                int pictureShareId = Convert.ToInt32(new PictureShareRepository().SaveSharePicture(objPictureShare));
                                if (pictureShareId > 0)
                                    strmsg = "1";
                                else
                                    strmsg = "0";
                            }
                            else if (ContentType == "Video")
                            {
                                Pro_VideoShareMaster objVideoShare = new Pro_VideoShareMaster();
                                objVideoShare.UserId = webposter.LoginUserId;
                                objVideoShare.VideoId = webposter.ContentId;
                                objVideoShare.CreatedOn = DateTime.UtcNow.ToString();
                                objVideoShare.ShareId = webposter.FromUserId;
                                int VideoShareId = Convert.ToInt32(new VideoShareRepository().SaveShareVideo(objVideoShare));
                                if (VideoShareId > 0)
                                    strmsg = "1";
                                else
                                    strmsg = "0";
                            }
                        }
                    }
                    return ServiceHelper.GetServiceJson(ServiceHelper.JsonType.ResultMessage, StatusConstants.Ok, strmsg);
                }
            );
            return task;
        }

        [HttpPost]
        [ActionName("AddChatToWebPoster1")]
        public dynamic AddChatToWebPoster1(Pro_WebPoster objWebPoster)
        {
            string msg = string.Empty;
            bool IsSuccess;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();


            if (objWebPoster.Share == 0)
            {
                long offset = Convert.ToInt64(objWebPoster.Offset);
                string path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["WebPosterUrl"]);
                if (objWebPoster.ContentType == "Image")
                    objWebPoster.ChatImgName = objWebPoster.FileName;
                else
                    objWebPoster.ChatVideoName = objWebPoster.FileName;
                if (objWebPoster.IsUploadingEnd == true)
                {
                    new Helpers.HelperFunctions().UploadFile(objWebPoster.FileName, objWebPoster.buffer, offset, path);
                    IsSuccess = false;
                }
                else
                {
                    IsSuccess = new Helpers.HelperFunctions().UploadFile(objWebPoster.FileName, objWebPoster.buffer, offset, path);
                    dicto.Add("Success", IsSuccess);
                }

                if (IsSuccess == false)
                {
                    Pro_webPosterChat objchat = new Pro_webPosterChat();
                    objchat.FromId = objWebPoster.LoginUserId;
                    objchat.ToId = objWebPoster.FromUserId;
                    objchat.GroupId = 0;
                    objchat.ChatOn = objWebPoster.CreatedOn;
                    if (objWebPoster.ContentType == "Image")
                    {
                        objchat.ContentType = "ChatImage";
                        objchat.Content = objWebPoster.ChatImgName;
                        //--------------Thumb image------------------------------------
                        if (objWebPoster.ContentType == "Image")
                            Helpers.HelperFunctions.SaveThumbImage(path + objWebPoster.FileName, 100, 100, "Thumb_");
                        //--------------End Thumb image--------------------------------
                    }
                    else if (objWebPoster.ContentType == "Video")
                    {
                        objchat.ContentType = "ChatVideo";
                        objchat.Content = objWebPoster.ChatVideoName;
                    }
                    else
                    {
                        objchat.ContentType = "ChatText";
                        objchat.Content = objWebPoster.TextMsg;
                    }

                    int webPosterId = Convert.ToInt32(new WebPosterChatRepository().SavewebPosterChat(objchat));
                    if (webPosterId > 0)
                    {
                        dicto.Add("Status", Convert.ToBoolean(1));
                    }
                    else
                    {
                        if (File.Exists(path + "/" + objWebPoster.FileName))
                        {
                            DeleteImageVideo(path + "/" + objWebPoster.FileName);
                            if (objchat.ContentType == "ChatImage")
                                DeleteImageVideo(path + "/" + "Thumb_" + objWebPoster.FileName);
                        }
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }

                }
            }
            else
            {
                Pro_WebPosterChatShare chatshare = new Pro_WebPosterChatShare();
                chatshare.UserId = objWebPoster.LoginUserId;
                chatshare.WPChatId = objWebPoster.ContentId;
                chatshare.ShareId = objWebPoster.FromUserId;
                chatshare.CreatedOn = objWebPoster.CreatedOn;
                int ChatId = Convert.ToInt32(new WebPosterChatShareRepository().SaveShareChat(chatshare));
                if (ChatId > 0)
                {
                    dicto.Add("Status", Convert.ToBoolean(1));
                }
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("AddChatToWebPoster")]
        public System.Threading.Tasks.Task<Dictionary<string, dynamic>> AddChatToWebPoster()
        {
            HttpRequestMessage request = Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            var webposter = new Pro_WebPoster();
            string strmsg = string.Empty;
            string ContentType = string.Empty;
            string strChatContent = string.Empty;
            var root = HttpContext.Current.Server.MapPath("~/Uploads/WebPoster");
            var provider = new MultipartFormDataStreamProvider(root);

            Image img = null;
            byte[] b = null;
            System.IO.FileInfo finfo = null;
            var webposterPic = "";
            var webposterVideo = "";

            var task = request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(o =>
                {
                    foreach (var key in provider.FormData.AllKeys)
                    {
                        var values = provider.FormData.GetValues(key);
                        if (values != null)
                            foreach (var val in values)
                            {
                                if (string.Equals(key, "Share", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.Share = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "LoginUserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.LoginUserId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "FromUserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.FromUserId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "ContentType", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        ContentType = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "ContentId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.ContentId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "TextMsg", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        strChatContent = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "CreatedOn", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.CreatedOn = Convert.ToString(val);
                                }
                                break;
                            }
                    }

                    if (webposter.LoginUserId > 0)
                    {
                        if (webposter.Share == 0)
                        {
                            Pro_webPosterChat objchat = new Pro_webPosterChat();
                            objchat.FromId = webposter.LoginUserId;
                            objchat.ToId = webposter.FromUserId;
                            objchat.GroupId = 0;
                            objchat.ChatOn = DateTime.UtcNow.ToString();
                            if (provider.FileData.Count != 0)
                            {
                                if (ContentType == "Image")
                                {
                                    //webposterPic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + webposter.LoginUserId + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                                    webposterPic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + webposter.LoginUserId + ".png";
                                    finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                                    img = System.Drawing.Image.FromFile(finfo.FullName);
                                    var converter = new System.Drawing.ImageConverter();
                                    b = (byte[])converter.ConvertTo(img, typeof(byte[]));
                                    //DateTime dt = Convert.ToDateTime(webposter.CreatedOn);
                                    objchat.ContentType = "ChatImage";
                                    objchat.Content = webposterPic;
                                    int pictureId = Convert.ToInt32(new WebPosterChatRepository().SavewebPosterChat(objchat));

                                    if (pictureId > 0)
                                    {
                                        //----Image upload-----
                                        Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, webposterPic), img.Width, img.Height);
                                        Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, "Thumb_" + webposterPic), 100, 100);
                                        img.Dispose();
                                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                                        strmsg = "1";
                                        //----End Image upload-----
                                    }
                                    else
                                        strmsg = "0";
                                }
                                else if (ContentType == "Video")
                                {
                                    webposterVideo = Helpers.HelperFunctions.CreateUniqueFileName() + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                                    DateTime dt = DateTime.UtcNow;
                                    objchat.ContentType = "ChatVideo";
                                    objchat.Content = webposterVideo;
                                    int VideoId = Convert.ToInt32(new WebPosterChatRepository().SavewebPosterChat(objchat));
                                    if (VideoId > 0)
                                    {
                                        //----video upload-----
                                        finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                                        System.IO.File.Move(finfo.FullName, System.IO.Path.Combine(root, webposterVideo));
                                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                                        strmsg = "1";
                                        //----End video upload-----
                                    }
                                    else
                                        strmsg = "0";
                                }
                            }
                            if (ContentType == "TextMsg")
                            {
                                objchat.ContentType = "ChatText";
                                objchat.Content = strChatContent;
                                int ChatId = Convert.ToInt32(new WebPosterChatRepository().SavewebPosterChat(objchat));
                                if (ChatId > 0)
                                {
                                    strmsg = "1";
                                }
                                else
                                    strmsg = "0";
                            }
                        }
                        else
                        {
                            Pro_WebPosterChatShare chatshare = new Pro_WebPosterChatShare();
                            chatshare.UserId = webposter.LoginUserId;
                            chatshare.WPChatId = webposter.ContentId;
                            chatshare.ShareId = webposter.FromUserId;
                            chatshare.CreatedOn = DateTime.UtcNow.ToString();
                            int ChatId = Convert.ToInt32(new WebPosterChatShareRepository().SaveShareChat(chatshare));
                            if (ChatId > 0)
                            {
                                strmsg = "1";
                            }
                            else
                                strmsg = "0";
                        }
                    }
                    return ServiceHelper.GetServiceJson(ServiceHelper.JsonType.ResultMessage, StatusConstants.Ok, strmsg);
                }
            );
            return task;
        }

        [HttpPost]
        [ActionName("GetDatesForWebposter")]
        public dynamic GetDatesForWebposter(Pro_WebPoster objPro_WebPoster)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var DateList = new WebPosterRepository().GetDatesForWebPoster(objPro_WebPoster);

            if (DateList.Count > 0)
            {
                if(DateList[0] == "2")
                    dicto.Add("Status", Convert.ToInt32(DateList[0]));
                else
                    dicto.Add("Result", DateList);
            }
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetDetailsForWebPoster")]
        public dynamic GetDetailsForWebPoster(Pro_WebPoster objProWebPoster)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var DateList = new WebPosterRepository().GetDetailsForWebPosterByDate(objProWebPoster);

            if (DateList.Count > 0)
                dicto.Add("Result",DateList);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("WelcomeHome")]
        public dynamic WelcomeHome(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var CountDetail = new UserRepository().InsertLatLongAndUserStatus(user);

            if (user.UserId > 0)
                dicto.Add("Result",CountDetail);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }


        [HttpPost]
        [ActionName("UserStatus")]
        public dynamic UserStatus(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var CountDetail = new UserRepository().UserStatus(user);

            if (CountDetail > 0)
                 dicto.Add("Result",CountDetail);
            else
                 dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("UserPrivacySetting")] //for on and of
        public dynamic UserPrivacySetting(Pro_UserPrivacySetting user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserDetail = new UserRepository().UpdatePrivacySetting(user);

            if (UserDetail > 0)
                dicto.Add("Status", Convert.ToBoolean(1));
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }
        #endregion


        #region News

        [HttpPost]
        [ActionName("GetNewsCount")]
        public dynamic GetNewsCount(Pro_News objNews)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var newsCount = new NewsRepository().GetNewsCount(objNews);

            if (newsCount > 0)
                dicto.Add("Result",newsCount);
            else
                 dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }


        [HttpPost]
        [ActionName("GetLatestNewsList")]
        /* UserID,ViewOn*/
        public dynamic GetLatestNewsList(Pro_News objProNews)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var DateList = new NewsRepository().GetLatestNewsList(objProNews);

            if (DateList.Count > 0)
                dicto.Add("Result", DateList);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("SetContentSeenByUser")]
        /* UserID,ViewOn*/
        public dynamic SetContentSeenByUser(Pro_News objProNews)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            int NewsId = Convert.ToInt32(new NewsRepository().SetContentSeenByUser(objProNews));

            if (NewsId > 0)
                dicto.Add("Status", Convert.ToBoolean(1));
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        //[HttpPost]
        //[ActionName("FriendScreen")]
        //public dynamic FriendScreen(Pro_ChatHistoryMaster objProChat)
        //{
        //    Dictionary<string, dynamic> dicto;
        //    var DateList = new ChatHistoryRepository().GetDetailForFriendScreen(objProChat);

        //    if (DateList.Count > 0)
        //        dicto = ServiceHelper.GetServiceJson(ServiceHelper.JsonType.Data, StatusConstants.Ok, DateList, "", true);
        //    else
        //    {
        //        dicto = new Dictionary<string, dynamic>();
        //        dicto.Add("Result", "Records not found");
        //        if (Convert.ToString(objProChat.ChatOn) == "1/1/1900 12:00:00 AM")
        //            dicto.Add("Date", new UserRepository().Getdate());
        //    }
        //    return dicto;
        //}

        [HttpPost]
        [ActionName("Truncate")]
        public dynamic Truncate()
        {
            Dictionary<string, dynamic> dicto;
            var detail = new UserRepository().Truncate();

            if (detail)
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "Truncated data Successfully");
            }
            else
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "Truncate fail");
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("SearchUserByName")]
        public dynamic SearchUserByName(Pro_UserMaster User)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var DateList = new UserRepository().GetUserBySerachName(User);

            if (DateList.Count > 0)
                dicto.Add("Result", DateList);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("AddAsFriend")]
        public dynamic AddAsFriend(Pro_UserContact User)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var Userid = Convert.ToInt32(new UserContactRepository().AddAsFriend(User));
            if (Userid > 0)
            {
                dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("AuthenticateUserForRestore")]
        public dynamic AuthenticateUserForRestore(Pro_UserMaster User)
        {
            Dictionary<string, dynamic> dicto;
            var detail = new UserRepository().RestoreUser(User);

            if (detail == -1)
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "ContactNo does not exists");
            }
            else if (detail == -2)
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "Email does not exists");
            }
            else if (detail == 0)
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "Email and contact does not exists");
            }
            else
            {
                Random rnd = new Random();
                string code = rnd.Next(1000, 10000).ToString();
                if (code.Length == 3)
                    code = code + "0";
                else if (code.Length == 2)
                    code = code + "00";
                dicto = new Dictionary<string, dynamic>();


                //-------------------Send Email with varfication code--------------
                bool EmailStatus = EmailHelper.SendEmailForVarificationCode(User.EmailId, code, User.ContactNo);
                if (EmailStatus == true)
                {
                    dicto.Add("code", code);
                   // dicto.Add("Status", Convert.ToBoolean(1));
                }
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("RestoreUser")]
        public dynamic RestoreUser(Pro_UserMaster User)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var UserId = new UserRepository().RestoreUser(User);
            if (UserId > 0)
            {
                var UserProfile = new UserRepository().GetUserProfile(UserId);
                var FriendList = new UserContactRepository().GetContactList(UserId);
                if (UserProfile.UserId > 0)
                    dicto.Add("UserDetail", UserProfile);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
                //dicto.Add("RegistrationDate", new UserRepository().Getdate());

                if(FriendList.Count > 0)
                    dicto.Add("FriendList", FriendList);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));

                return dicto;
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("checkForContact")]
        public dynamic checkForContact(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var UserDetails = new ContactDetailsRepository().checkForContact(user.UserId, user.ContactNo);
            if (UserDetails.UserId > 0)
               dicto.Add("Result",UserDetails);
            else
                dicto.Add("Status", "0");
            return dicto;
        }

        [HttpPost]
        [ActionName("CustomPrivacySetting")]
        public dynamic CustomPrivacySetting(Pro_PrivacySetting user)
        {
            string UserSetting = string.Empty;
            string GroupSetting = string.Empty;
            int i = 0;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();

            Pro_UserPrivacySetting objuser = new Pro_UserPrivacySetting();
            objuser.UserId = user.UserId;
            objuser.PrivacySetting = 2;
            var UserDetail = new UserRepository().UpdatePrivacySetting(objuser);
            if (UserDetail > 0)
            {
                UserSetting = Convert.ToString(user.UserSettingArray);
                GroupSetting = Convert.ToString(user.GroupSettingArray);

                //---User Setting array------------
                JavaScriptSerializer jss = new JavaScriptSerializer();
                List<Pro_UserPrivacySetting_Api> UserSettingList = jss.Deserialize<List<Pro_UserPrivacySetting_Api>>(UserSetting);
                //---End--------------------------

                //---User Setting array------------
                JavaScriptSerializer jss1 = new JavaScriptSerializer();
                List<Pro_GroupPrivacySetting_Api> GroupSettingList = jss1.Deserialize<List<Pro_GroupPrivacySetting_Api>>(GroupSetting);
                //---End--------------------------

                string result = new PrivacySettingRepository().InsertPrivacySetting(UserSettingList, GroupSettingList, user.UserId);
                if (result == "1")
                {
                    dicto.Add("Status", Convert.ToBoolean(1));
                }
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }
        #endregion

        [HttpPost]
        [ActionName("UploadVideo")]
        public dynamic Upload(Pro_VideoMaster_Api video)
        {
            Dictionary<string, dynamic> dicto;
            // byte[] b = Encoding.ASCII.GetBytes(video.buffer);
            long offset = Convert.ToInt64(video.Offset);
            string path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["upload_path"]);
            var IsSuccess = new Helpers.HelperFunctions().UploadFile(video.FileName, video.buffer, offset, path);

            dicto = new Dictionary<string, dynamic>();
            dicto.Add("Result", IsSuccess);
            dicto.Add("Message", (IsSuccess == true ? "Success" : "Failure"));

            return dicto;

        }

        [HttpPost]
        [ActionName("InsertChatWithImageOrVideo1")]
        public dynamic InsertChatWithImageOrVideo1(Pro_ChatHistoryMaster chat)
        {
            string msg = string.Empty;
            bool IsSuccess;
            int chatId = 0;
            Pro_ChatHistoryMaster objchat = new Pro_ChatHistoryMaster();
            Pro_ChatDateDetail Chat = new Pro_ChatDateDetail();
            Pro_GroupChatDateDetail ChatDetail = new Pro_GroupChatDateDetail();
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            long offset = Convert.ToInt64(chat.Offset);
            string path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["UploadChatImageVideo"]);

            if (chat.Upload == "Image")
                chat.ImagePath = chat.FileName;
            else
                chat.VideoPath = chat.FileName;
            if (chat.IsUploadingEnd == true)
            {
                new Helpers.HelperFunctions().UploadFile(chat.FileName, chat.buffer, offset, path);
                IsSuccess = false;
            }
            else
            {
                IsSuccess = new Helpers.HelperFunctions().UploadFile(chat.FileName, chat.buffer, offset, path);
                dicto.Add("Success", IsSuccess);
            }

            if (IsSuccess == false)
            {
                //--------------Thumb image------------------------------------
                if (chat.Upload == "Image")
                    Helpers.HelperFunctions.SaveThumbImage(path + chat.FileName, 100, 100, "Thumb_");
                //--------------End Thumb image--------------------------------
                //--------------Insert Process----------------------------------
                if (chat.GroupId != 0)
                {
                    ChatDetail = new ChatHistoryRepository().InsertGroupChat(chat);
                    if (ChatDetail.Status == true)
                        dicto.Add("Result", ChatDetail);
                    else
                    {
                        if (File.Exists(path + "/" + chat.FileName))
                            DeleteImageVideo(path + "/" + chat.FileName);
                        if (chat.Upload == "Image")
                            DeleteImageVideo(path + "/" + "Thumb_" + chat.FileName);
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }
                }
                else
                {
                    Chat = new ChatHistoryRepository().SaveChat(chat);
                    //chatId = Convert.ToInt32(new ChatHistoryRepository().SaveChat(chathistory));
                    if (Chat.ServerID > 0)
                    {
                        dicto.Add("Result", Chat);
                        //dicto.Add("Status", Convert.ToBoolean(1));
                    }
                    else
                    {
                        if (File.Exists(path + "/" + chat.FileName))
                        {
                            DeleteImageVideo(path + "/" + chat.FileName);
                            if (chat.Upload == "Image")
                                DeleteImageVideo(path + "/" + "Thumb_" + chat.FileName);
                        }
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }
                }
            }
            //--------------End Insert Process-------------
            return dicto;
        }

        //[HttpPost]
        //[ActionName("UploadVideo1")]
        //public string UploadVideo1(Pro_VideoMaster_Api1 video)
        //{
        //    //Dictionary<string, dynamic> dicto;
        //    string FilePath=video.File;
        //    int Offset = 0; // starting offset.
        //    int ChunkSize = 65536;

        //    byte[] Buffer = new byte[ChunkSize];
        //    //opening the file for read.
        //    FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
        //    //creating the ServiceSoapClient which will allow to connect to the service.
        //    //WSservice.ServiceSoapClient soap_client = new WSservice.ServiceSoapClient();
        //    try
        //    {
        //        long FileSize = new FileInfo(FilePath).Length; // File size of file being uploaded.
        //        // reading the file.
        //        fs.Position = Offset;
        //        int BytesRead = 0;

        //        while (Offset != FileSize) // continue uploading the file chunks until offset = file size.
        //        {
        //            BytesRead = fs.Read(Buffer, 0, ChunkSize); // read the next chunk
        //            // (if it exists) into the buffer.
        //            // the while loop will terminate if there is nothing left to read
        //            // check if this is the last chunk and resize the buffer as needed
        //            // to avoid sending a mostly empty buffer
        //            // (could be 10Mb of 000000000000s in a large chunk)
        //            if (BytesRead != Buffer.Length)
        //            {
        //                ChunkSize = BytesRead;
        //                byte[] TrimmedBuffer = new byte[BytesRead];
        //                Array.Copy(Buffer, TrimmedBuffer, BytesRead);
        //                Buffer = TrimmedBuffer; // the trimmed buffer should become the new 'buffer'
        //            }
        //            // send this chunk to the server. it is sent as a byte[] parameter,
        //            // but the client and server have been configured to encode byte[] using MTOM.
        //            bool ChunkAppened = new VideoRepository().UploadFile(Path.GetFileName(FilePath), Buffer, Offset);
        //            if (!ChunkAppened)
        //            {
        //                break;
        //            }

        //            // Offset is only updated AFTER a successful send of the bytes.
        //            Offset += BytesRead; // save the offset position for resume
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //    }
        //    finally
        //    {
        //        fs.Close();
        //    }

        //    return "Success";

        //}

        [HttpPost]
        [ActionName("InsertComment")] //for on and of
        public dynamic InsertComment(Pro_CommentMaster Comment)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var CommentId = new CommentMasterRepository().SaveComment(Comment);

            if (Convert.ToInt32(CommentId) > 0)
            {
               // dicto.Add("CommentId", Convert.ToInt32(CommentId));
                dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("InsertLike")] //for on and of
        public dynamic InsertLike(Pro_LikeMaster Like)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var LikeId = new LikeMasterRepository().SaveLike(Like);

            if (Convert.ToInt32(LikeId) > 0)
            {
                //dicto.Add("LikeId", Convert.ToInt32(LikeId));
                dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("DeleteComment")] //for on and of
        public dynamic DeleteComment(Pro_CommentMaster Comment)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var CommentId = new CommentMasterRepository().DeleteComment(Comment.CommentId);

            if (Convert.ToInt32(CommentId) > 0)
            {
                dicto.Add("CommentId", Convert.ToInt32(CommentId));
                //dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("DeleteLike")] //for on and of
        public dynamic DeleteLike(Pro_LikeMaster Like)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var LikeId = new LikeMasterRepository().DeleteLike(Like.LikeId);

            if (Convert.ToInt32(LikeId) > 0)
            {
                dicto.Add("LikeId", Convert.ToInt32(LikeId));
                //dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }


        [HttpPost]
        [ActionName("GetComment")] //for on and of
        public dynamic GetComment(Pro_CommentMaster Comment)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var CommentList = new CommentMasterRepository().GetComment(Comment);

            if (CommentList.Count > 0)
                dicto.Add("Result", CommentList);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("GetLikeCount")] //for on and of
        public dynamic GetLikeCount(Pro_LikeMaster Like)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var LikeCount = new LikeMasterRepository().GetLikeCount(Like);

            if (LikeCount > 0)
                dicto.Add("LikeCount", LikeCount);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetRecentMsg")]
        public dynamic GetRecentMsg(Pro_ChatHistoryMaster Chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>(); ;
            List<Pro_FriendScreen_Api> chats = new ChatHistoryRepository().GetRecentMsg(Chat);
            if (chats.Count > 0)
            {
                dicto.Add("Result", chats);
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        //-------Add by Nirmal 7-01-2013-------
        [HttpPost]
        [ActionName("GetHighlightedContent")] //for send total like count and other information
        public dynamic GetLikeCount(Pro_LikesMaster objlikes)
        {
            const int pageSize = 10;
            int count = 0;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var TotalLikecount = new LikeMasterRepository().GetAllLikesCount(objlikes.RecordIndex, objlikes.ContentType);
            if (TotalLikecount.Count > 0)
            {
                dicto.Add("Result", TotalLikecount);
                if (TotalLikecount.Count < pageSize || ((objlikes.RecordIndex + pageSize) == count))
                {
                    dicto.Add("Count", TotalLikecount.Count);
                    dicto.Add("Next", false);
                }
                else
                {
                    dicto.Add("Count", TotalLikecount.Count);
                    dicto.Add("Next", true);
                }
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("GetHighlightedComments")]
        public dynamic GetComments(Pro_CommentsMaster objcomments)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var TotalComments = new LikeMasterRepository().GetAllComments(objcomments.ContentId, objcomments.ContentType);
            if (TotalComments.Count > 0)
            {
                dicto.Add("Result", TotalComments);
                dicto.Add("Count", TotalComments.Count);
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        //------------End-----------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Gammers.Models;
using Gammers.Repository;
using Gammers.Helpers;
using System.Web.Optimization;
using System.Threading.Tasks;
using System.Web;
using System.IO;
using System.Drawing;
using System.ComponentModel;
using System.Web.Hosting;
using System.Drawing.Imaging;
using System.Net.Http.Headers;
using System.Diagnostics;
using HoiioSDK.NET;
using Newtonsoft.Json;
using System.Windows.Forms;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web.Script.Serialization;
using System.Configuration;
using System.Globalization;
using System.Data;

namespace Gammers.Controllers
{
    public class UserController : ApiController
    {

        [HttpPost]
        [ActionName("AuthenticateUser")]
        public dynamic AuthenticateUser(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();

            var Result = Convert.ToInt32(new UserRepository().AuthentucateUser(user.EmailId, user.ContactNo));
            if (Result == -1)
                dicto = ServiceHelper.GetServiceJson(ServiceHelper.JsonType.Error, StatusConstants.Error, null, "Email does not exists."); // msg as per client said
            else if (Result == -2)
                dicto = ServiceHelper.GetServiceJson(ServiceHelper.JsonType.Error, StatusConstants.Error, null, "Contact does not exists."); //msg as per client said
            else
            {
                Random rnd = new Random();
                string code = rnd.Next(1000, 10000).ToString();
                if (code.Length == 3)
                    code = code + "0";
                else if (code.Length == 2)
                    code = code + "00";
                dicto = new Dictionary<string, dynamic>();


                //-------------------Send Email with varfication code--------------
                bool EmailStatus = EmailHelper.SendEmailForVarificationCode(user.EmailId, code, user.ContactNo);
                if (EmailStatus == true)
                {
                    dicto.Add("code", code);
                    dicto.Add("Result", "Email Send Successfully");
                }
                else
                    dicto.Add("Result", "Email Sending fail");
                //-------------------End-------------------------------------------
            }
            return dicto;
        }

        private int GetTempId(string emailid)
        {
            if (emailid == Convert.ToString("VGarha@gmail.com").ToLower())
                return 1;
            else if (emailid == Convert.ToString("MiMart187@gmail.com").ToLower())
                return 2;
            else if (emailid == Convert.ToString("Geena6992@gmail.com").ToLower())
                return 3;
            else if (emailid == Convert.ToString("dipen.panchasara@ifuturz.com").ToLower())
                return 4;
            else if (emailid == Convert.ToString("mukesh.verma@ifuturz.com").ToLower())
                return 5;
            else if (emailid == Convert.ToString("rajan.samouker@ifuturz.com").ToLower())
                return 6;
            else
                return 0;
        }

        [HttpPost]
        [ActionName("RegisterUser")]
        public dynamic RegisterUser(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            user.DeviceId = user.DeviceId.Replace(" ","");
            Pro_UserDetail Userdetail = new UserRepository().InsertUser(user);
            if (Userdetail.UserId > 0)
            {
                dicto.Add("Message", Userdetail.Message);
                dicto.Add("UserId", Userdetail.UserId);
                dicto.Add("CreatedOn", Userdetail.CreatedOn);
            }
            else
            {
                dicto.Add("Message", Userdetail.Message);
                dicto.Add("UserId", Userdetail.UserId);
                dicto.Add("CreatedOn", Userdetail.CreatedOn);
            }
         
            return dicto;
        }

        [HttpPost]
        [ActionName("RefreshContacts")]
        public dynamic RefreshContacts(Pro_ContactDetails user)
        {
            int i = 0;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            i = Convert.ToInt32(new ContactDetailsRepository().UpdateIsFriend(user.UserId, user.CreatedOn));

            if (i == 1)
            {
                var ContactDetails = new ContactDetailsRepository().GetFriendList(user.UserId, user.CreatedOn);
                if (ContactDetails.Count > 0)
                    dicto.Add("Result", ContactDetails);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("InsertContactDetails")]
        public dynamic InsertContactDetails(Pro_ContactDetails user)
        {
            string contacts = string.Empty;
            int i = 0;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            contacts = Convert.ToString(user.ContactArray);
            JavaScriptSerializer jss = new JavaScriptSerializer();
            List<Pro_ContactDetails_Api> Contactlist = jss.Deserialize<List<Pro_ContactDetails_Api>>(contacts);
            string result = new ContactDetailsRepository().InsertContacts(Contactlist, user.UserId, user.CreatedOn);
            if (result == "Success")
            {
                i = Convert.ToInt32(new ContactDetailsRepository().UpdateIsFriend(user.UserId, user.CreatedOn));
            }
            if (i == 1)
            {
                var ContactDetails = new ContactDetailsRepository().GetFriendList(user.UserId, user.CreatedOn);
                if (ContactDetails != null)
                    dicto.Add("Result", ContactDetails);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("RestoreFriendList")]
        public dynamic RestoreFriendList(Pro_FriendsContactDetails_Api user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserDetails = new ContactDetailsRepository().RestoreFriendList(Convert.ToInt32(user.UserId));
            if (UserDetails.Count > 0)
                dicto.Add("Result", UserDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetFeaturedMember")]
        public dynamic GetFeaturedMember(Pro_UserMaster_Api user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserDetails = new UserRepository().GetFeaturedMember(user.UserId);
            if (UserDetails.UserId > 0)
                dicto.Add("Result", UserDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetHighlightedPicture")]
        public dynamic GetHighlightedPicture(Pro_PictureShareMaster_Api Picture)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var PictureDetails = new PictureShareRepository().GetTotalSharePicture(Picture.UserId);
            if (PictureDetails.Count > 0)
                dicto.Add("Result", PictureDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetHighlightedVideos")]
        public dynamic GetHighlightedVideos(Pro_VideoShareMaster_Api Video)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var VideoDetails = new VideoShareRepository().GetTotalShareVideos(Video.UserId);
            if (VideoDetails.Count > 0)
                dicto.Add("Result", VideoDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetUserContactDetails")]
        public dynamic GetUserContactDetails(Pro_UserContact user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var UserContactDetails = new UserContactRepository().GetUserContactDetails(user.UserId, user.Flag);
            if (UserContactDetails.Count > 0)
                dicto.Add("Result", UserContactDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetUserProfile")]
        public dynamic GetUserProfile(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserProfile = new UserRepository().GetUserProfile(user.UserId);

            if (UserProfile.UserId > 0)
                dicto.Add("Result",UserProfile);
            else
                dicto.Add("Status",Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("UpdateProfileAndProfilePic")]
        public System.Threading.Tasks.Task<Dictionary<string, dynamic>> UpdateProfileAndProfilePic()
        {
            HttpRequestMessage request = Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            var user = new Pro_UserMaster();
            bool Status = false;
            var root = HttpContext.Current.Server.MapPath("~/Uploads/ProfilePicture");
            var provider = new MultipartFormDataStreamProvider(root);

            var task = request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(o =>
                {
                    foreach (var key in provider.FormData.AllKeys)
                    {
                        var values = provider.FormData.GetValues(key);
                        if (values != null)
                            foreach (var val in values)
                            {
                                if (string.Equals(key, "UserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.UserId = Convert.ToInt32(val);
                                }
                                if (string.Equals(key, "UserName", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.UserName = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Sex", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Sex = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Birthdate", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Birthdate = Convert.ToDateTime(val);
                                }
                                else if (string.Equals(key, "AboutYou", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.AboutYou = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Intrestes", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Intrestes = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Hobbies", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Hobbies = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Favoritemovies", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Favoritemovies = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "LookingFor", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.LookingFor = Convert.ToString(val);
                                }
                                break;
                            }
                    }

                    if (user.UserId > 0)
                    {
                        if (provider.FileData.Count != 0)
                        {
                            string OldPic = new UserRepository().GetProfilePic(user.UserId);
                            if (!string.IsNullOrEmpty(OldPic))
                            {
                                if (File.Exists(root + "/" + OldPic))
                                {
                                    File.Delete(root + "/" + OldPic);
                                    File.Delete(root + "/" + "Thumb_" + OldPic);
                                }
                            }
                            //var ProfilePic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + user.UserId + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                            //var ProfilePic = "ProfilePic_" + user.UserId + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                            var ProfilePic = "ProfilePic_" + user.UserId + ".png";
                            var finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                            var img = System.Drawing.Image.FromFile(finfo.FullName);
                            //img = Helpers.ImageExtensions.Resize(img, Width, Height);
                            var converter = new System.Drawing.ImageConverter();
                            var b = (byte[])converter.ConvertTo(img, typeof(byte[]));
                            user.ProfilePic = ProfilePic;
                            user.Mode = "UpdateProfilePic";
                            int retval = Convert.ToInt32(new UserRepository().SaveProfile(user));
                            Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, ProfilePic), img.Width, img.Height);
                            Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, "Thumb_" + ProfilePic), 100, 100);
                            img.Dispose();
                            Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                            //System.IO.File.Move(finfo.FullName, System.IO.Path.Combine(root, userImage));
                            if (retval == 0)
                            {
                                if (File.Exists(root + "/" + ProfilePic))
                                {
                                    File.Delete(root + "/" + ProfilePic);
                                    File.Delete(root + "/" + "Thumb_" + ProfilePic);
                                }
                                Status =Convert.ToBoolean(0);
                            }
                        }

                        user.Mode = "UpdateProfile";
                        int Returnval = Convert.ToInt32(new UserRepository().SaveProfile(user));
                        if (Returnval > 0)
                            Status = Convert.ToBoolean(1);
                        else
                            Status = Convert.ToBoolean(0);

                    }
                    Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
                    dicto.Add("Status", Status);
                    return dicto;
                   // return ServiceHelper.GetServiceJson(ServiceHelper.JsonType.ResultMessage, StatusConstants.Ok, Status);
                }
            );
            return task;
        }

        public dynamic GetVideo(int id)
        {
            Pro_VideoMaster objpicture = new Pro_VideoMaster();
            objpicture = new VideoRepository().GetVideoById(id);
            byte[] Content = objpicture.VideoContent;
            //MemoryStream ms = new MemoryStream(Content);

            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream(Content);
            object rval = formatter.Deserialize(stream);
            stream.Close();
            return rval;
        }

        //public HttpResponseMessage Get(int id)
        //{
        //    Pro_PictureMaster objpicture = new Pro_PictureMaster();
        //    objpicture = new PictureRepository().GetPictureById(id);
        //    byte[] imgData = objpicture.ImageContent;
        //    MemoryStream ms = new MemoryStream(imgData);
        //    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
        //    response.Content = new StreamContent(ms);
        //    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");

        //    return response;
        //}
        [HttpPost]
        [ActionName("InsertChat")]
        public dynamic InsertChat(Pro_ChatHistoryMaster chatHistory)
        {
            Dictionary<string, dynamic> dicto;
            if (chatHistory.GroupId != 0)
            {
                Pro_GroupChatDateDetail chat = new ChatHistoryRepository().InsertGroupChat(chatHistory);
                dicto = new Dictionary<string, dynamic>();
                if (chat.Status == true)
                {
                    //dicto.Add("ChatId", ChatId);
                    dicto.Add("Result", chat);
                }
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            else
            {
                Pro_ChatDateDetail Chat = new ChatHistoryRepository().SaveChat(chatHistory);
                dicto = new Dictionary<string, dynamic>();
                if (Chat.ServerID > 0)
                {
                    dicto.Add("Result", Chat);
                    //dicto.Add("Status", Convert.ToBoolean(1));
                }
                else
                {
                    dicto.Add("Status", Convert.ToBoolean(0));
                }
            }

            return dicto;

        }

        [HttpPost]
        [ActionName("InsertChatwithImageOrVideo")]
        public System.Threading.Tasks.Task<Dictionary<string, dynamic>> InsertChatwithImageOrVideo()
        {
            HttpRequestMessage request = Request;
            Pro_GroupChatDateDetail chatdetail = new Pro_GroupChatDateDetail();
            Pro_ChatDateDetail Chat = new Pro_ChatDateDetail();
            int Height = 0;
            int Width = 0;
            string Upload = string.Empty;
            string FileName = string.Empty;
            byte[] buffer = null;
            long offset = 0;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            var chathistory = new Pro_ChatHistoryMaster();
            string strmsg = string.Empty;
            //var root =Helpers.ConstantValues.RootUrl;
            var root = HttpContext.Current.Server.MapPath("~/Uploads/ChatHistory");
            var provider = new MultipartFormDataStreamProvider(root);
            Dictionary<string, dynamic> dicto = null;
            var task = request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(o =>
                {
                    foreach (var key in provider.FormData.AllKeys)
                    {
                        var values = provider.FormData.GetValues(key);
                        if (values != null)
                            foreach (var val in values)
                            {
                                if (string.Equals(key, "FromId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        chathistory.FromId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "ToId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        chathistory.ToId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "GroupId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        chathistory.GroupId = Convert.ToInt32(val);
                                }
                                //else if (string.Equals(key, "ChatOn", StringComparison.OrdinalIgnoreCase))
                                //{
                                //    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                //        chathistory.ChatOn = Convert.ToDateTime(val);
                                //}
                                else if (string.Equals(key, "Upload", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        Upload = val;
                                }
                                //else if (string.Equals(key, "FileName", StringComparison.OrdinalIgnoreCase))
                                //{
                                //    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                //        FileName = val;
                                //}
                                //else if (string.Equals(key, "buffer", StringComparison.OrdinalIgnoreCase))
                                //{
                                //    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                //        buffer = Encoding.ASCII.GetBytes(val);
                                //}
                                //else if (string.Equals(key, "Offset", StringComparison.OrdinalIgnoreCase))
                                //{
                                //    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                //        offset =  Convert.ToInt64(val);
                                //}
                                break;
                            }
                    }

                    if (Upload == "Image")
                    {
                        var chatId = 0;
                        string msg = string.Empty;

                        //var userImage = Helpers.HelperFunctions.CreateUniqueFileName() + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                        var userImage = Helpers.HelperFunctions.CreateUniqueFileName() + ".png";
                        chathistory.ImagePath = userImage;

                        var finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                        var img = System.Drawing.Image.FromFile(finfo.FullName);
                        //img = Helpers.ImageExtensions.Resize(img, Width, Height);

                        var converter = new System.Drawing.ImageConverter();
                        var b = (byte[])converter.ConvertTo(img, typeof(byte[]));
                        bool retval = Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, userImage), img.Width, img.Height);

                        img.Dispose();
                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                        dicto = new Dictionary<string, dynamic>();
                        if (retval)
                        {
                            Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, "Thumb_" + userImage), 100, 100);
                            if (chathistory.GroupId != 0)
                            {
                                chatdetail = new ChatHistoryRepository().InsertGroupChat(chathistory);
                                if (chatdetail.Status == true)
                                {
                                    dicto.Add("Result", chatdetail);
                                    dicto.Add("Message", "File Uploaded Successfully");
                                }
                                else
                                {
                                    if (File.Exists(root + "/" + userImage))
                                        DeleteImageVideo(root + "/" + userImage);
                                    dicto.Add("Message", msg);
                                }
                            }
                            else
                            {
                                Chat = new ChatHistoryRepository().SaveChat(chathistory);
                                //chatId = Convert.ToInt32(new ChatHistoryRepository().SaveChat(chathistory));
                                if (Chat.ServerID > 0)
                                {
                                    dicto.Add("Result", Chat);
                                    dicto.Add("Message", "File Uploaded Successfully");
                                }
                                else
                                {
                                    if (File.Exists(root + "/" + userImage))
                                    {
                                        DeleteImageVideo(root + "/" + userImage);
                                        DeleteImageVideo(root + "/" + userImage + "_Thumb");
                                    }
                                    dicto.Add("Message", "File Upload fail");
                                }
                            }
                        }
                        else
                        {
                            dicto.Add("Message", "File Uploaded Fail.");
                        }
                    }
                    else
                    {
                        dicto = new Dictionary<string, dynamic>();
                        string msg = string.Empty;
                        var UserVideo = Helpers.HelperFunctions.CreateUniqueFileName() + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                        chathistory.VideoPath = UserVideo;

                        var finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                        System.IO.File.Move(finfo.FullName, System.IO.Path.Combine(root, UserVideo));
                        if (File.Exists(root + "/" + UserVideo))
                        {
                            if (chathistory.GroupId != 0)
                            {
                                chatdetail = new ChatHistoryRepository().InsertGroupChat(chathistory);
                                if (chatdetail.Status == true)
                                {
                                    dicto.Add("Result", chatdetail);
                                    dicto.Add("Message", "File Uploaded Successfully");
                                }
                                else
                                {
                                    if (File.Exists(root + "/" + UserVideo))
                                        DeleteImageVideo(root + "/" + UserVideo);
                                    dicto.Add("Message", msg);
                                }
                            }
                            else
                            {
                                Chat = new ChatHistoryRepository().SaveChat(chathistory);
                                //chatId = Convert.ToInt32(new ChatHistoryRepository().SaveChat(chathistory));
                                if (Chat.ServerID > 0)
                                {
                                    dicto.Add("Result", Chat);
                                    dicto.Add("Message", "File Uploaded Successfully");
                                }
                                else
                                {
                                    if (File.Exists(root + "/" + UserVideo))
                                        DeleteImageVideo(root + "/" + UserVideo);
                                    dicto.Add("Message", "File Upload fail");
                                }
                            }
                        }

                    }

                    return dicto;
                    //return ServiceHelper.GetServiceJson(ServiceHelper.JsonType.ResultMessage, StatusConstants.Ok, strmsg);
                }
            );
            return task;
        }

        public void DeleteImageVideo(string FilePath)
        {
            File.Delete(FilePath);
        }

        [HttpPost]
        [ActionName("GetMyNewMsg")]
        public dynamic GetMyNewMsg(Pro_ChatHistoryMaster Chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            List<Pro_ChatHistoryDetail> chats = new ChatHistoryRepository().GetMyNewMsg(Chat.FromId, Chat.ToId, Chat.ChatDate);
            Pro_Status Status = new UserRepository().GetUserStatus(Chat.FromId,Chat.ChatId);

            if (chats.Count > 0)
            {
                dicto.Add("Result", chats);
                dicto.Add("IsOnline", Status.IsOnline);
                dicto.Add("IsTyping", Status.IsTyping);
            }
            else
            {
                dicto.Add("IsOnline", Status.IsOnline);
                dicto.Add("IsTyping", Status.IsTyping);
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("GetGroupChatHistory")]
        public dynamic GetGroupChatHistory(Pro_ChatHistoryMaster Chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            List<Pro_GroupChatHistoryDetail> chats = new ChatHistoryRepository().GetGroupChatHistory(Chat.ToId, Chat.GroupId);
            if (chats.Count > 0)
                dicto.Add("Result", chats);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetMyNewGroupMsg")]
        public dynamic GetMyNewGroupMsg(Pro_ChatHistoryMaster Chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            List<Pro_GroupChatHistoryDetail> chats = new ChatHistoryRepository().GetMyNewGroupMsg(Chat.ToId, Chat.GroupId, Chat.ChatDate);
            if (chats.Count > 0)
                dicto.Add("Result", chats);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("InsertGroup")]
        public dynamic InsertGroup(Pro_GroupMaster chatHistory)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            if (chatHistory.ListofUsers != null)
            {
                chatHistory.CreatedOn = DateTime.UtcNow;
                int GroupId = Convert.ToInt32(new GroupRepository().SaveGroup(chatHistory));
                if (GroupId > 0)
                    dicto.Add("GroupId", GroupId);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetAllGroupsByUserId")]
        public dynamic GetAllGroupsByUserId(int UserId)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserGroups = new GroupRepository().GetAllGroupsByUserId(UserId);
            if (UserGroups != null)
               dicto.Add("Result", UserGroups);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetGroupsByGroupId")]
        public dynamic GetGroupsByGroupId(int GroupId)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var groupsDetail = new GroupRepository().GetGroupsByGroupId(GroupId);

            if (groupsDetail != null)
                dicto.Add("Result", groupsDetail);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("GetAllGroupUser")]
        public dynamic GetAllGroupUser(Pro_GroupMaster chatHistory)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var groupsDetail = new GroupRepository().GetAllGroupUser(chatHistory.GroupId);

            if (groupsDetail != null)
               dicto.Add("Result", groupsDetail);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        #region Webposter current

        [HttpPost]
        [ActionName("AddToWebPoster1")]
        public dynamic AddToWebPoster1(Pro_WebPoster objWebPoster)
        {
            string strmsg = string.Empty;
            bool IsDataRemain;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();

            if (objWebPoster.Share == 0)
            {
                long offset = Convert.ToInt64(objWebPoster.Offset);
                string path = string.Empty;
                if (objWebPoster.FromCommunity == true)
                    path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["CommunityUrl"]);
                else
                    path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["WebPosterUrl"]);

                if (objWebPoster.ContentType == "Image")
                    objWebPoster.ChatImgName = objWebPoster.FileName;
                else
                    objWebPoster.ChatVideoName = objWebPoster.FileName;
                if (objWebPoster.IsUploadingEnd == true)
                {
                    new Helpers.HelperFunctions().UploadFile(objWebPoster.FileName, objWebPoster.buffer, offset, path);
                    IsDataRemain = false;
                }
                else
                {
                    IsDataRemain = new Helpers.HelperFunctions().UploadFile(objWebPoster.FileName, objWebPoster.buffer, offset, path);
                    dicto.Add("Success", IsDataRemain);
                }
                if (IsDataRemain == false)
                {
                    if (objWebPoster.ContentType == "Image")
                    {
                        //--------------Thumb image------------------------------------
                        if (objWebPoster.ContentType == "Image")
                            Helpers.HelperFunctions.SaveThumbImage(path + objWebPoster.FileName, 100, 100, "Thumb_");
                        //--------------End Thumb image--------------------------------


                        int pictureId = Convert.ToInt32(new PictureRepository().SaveUserPicture(objWebPoster.LoginUserId, objWebPoster.ChatImgName, Convert.ToDateTime(objWebPoster.CreatedOn), objWebPoster.FromCommunity));
                        if (pictureId > 0)
                        {
                            if (objWebPoster.FromCommunity == true)
                            {
                                dicto.Add("Status", Convert.ToBoolean(1));
                                dicto.Add("ContentId", pictureId);
                            }
                            else
                                dicto.Add("Status", Convert.ToBoolean(1));
                        }
                        else
                        {
                            if (File.Exists(path + "/" + objWebPoster.FileName))
                            {
                                DeleteImageVideo(path + "/" + objWebPoster.FileName);
                                DeleteImageVideo(path + "/" + "Thumb_" + objWebPoster.FileName);
                            }
                            dicto.Add("Status", Convert.ToBoolean(0));
                        }

                    }
                    else
                    {

                        int VideoId = Convert.ToInt32(new VideoRepository().SaveUserVideo(objWebPoster.LoginUserId, objWebPoster.ChatVideoName, Convert.ToDateTime(objWebPoster.CreatedOn), objWebPoster.FromCommunity));
                        if (VideoId > 0)
                        {
                            if (objWebPoster.FromCommunity == true)
                            {
                                dicto.Add("Status", Convert.ToBoolean(1));
                                dicto.Add("ContentId", VideoId);
                            }
                            else
                                dicto.Add("Status", Convert.ToBoolean(1));
                        }
                        else
                        {
                            if (File.Exists(path + "/" + objWebPoster.FileName))
                            {
                                DeleteImageVideo(path + "/" + objWebPoster.FileName);
                            }
                            dicto.Add("Status", Convert.ToBoolean(0));
                        }
                    }
                }
            }
            else //---If Share
            {
                if (objWebPoster.ContentType == "Image")
                {
                    Pro_PictureShareMaster objPictureShare = new Pro_PictureShareMaster();
                    objPictureShare.UserId = objWebPoster.LoginUserId;
                    objPictureShare.PictureId = objWebPoster.ContentId;
                    objPictureShare.ShareId = objWebPoster.FromUserId;
                    objPictureShare.CreatedOn = objWebPoster.CreatedOn;
                    objPictureShare.FromCommunity = objWebPoster.FromCommunity;
                    int pictureShareId = Convert.ToInt32(new PictureShareRepository().SaveSharePicture(objPictureShare));
                    if (pictureShareId > 0)
                    {
                        dicto.Add("Status", Convert.ToBoolean(1));
                    }
                    else
                    {
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }
                }
                else
                {
                    Pro_VideoShareMaster objVideoShare = new Pro_VideoShareMaster();
                    objVideoShare.UserId = objWebPoster.LoginUserId;
                    objVideoShare.VideoId = objWebPoster.ContentId;
                    objVideoShare.CreatedOn = DateTime.UtcNow.ToString();
                    objVideoShare.ShareId = objWebPoster.FromUserId;
                    objVideoShare.FromCommunity = objWebPoster.FromCommunity;
                    int VideoShareId = Convert.ToInt32(new VideoShareRepository().SaveShareVideo(objVideoShare));
                    if (VideoShareId > 0)
                    {
                        dicto.Add("Status", Convert.ToBoolean(1));
                    }
                    else
                    {
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }
                }
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("AddToWebPoster")]
        public System.Threading.Tasks.Task<Dictionary<string, dynamic>> AddToWebPoster()
        {
            HttpRequestMessage request = Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            var webposter = new Pro_WebPoster();
            string strmsg = string.Empty;
            string ContentType = string.Empty;
            string strChatContent = string.Empty;
            var root = HttpContext.Current.Server.MapPath("~/Uploads/WebPoster");
            var provider = new MultipartFormDataStreamProvider(root);

            Image img = null;
            byte[] b = null;
            System.IO.FileInfo finfo = null;
            var webposterPic = "";
            var webposterVideo = "";

            var task = request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(o =>
                {
                    foreach (var key in provider.FormData.AllKeys)
                    {
                        var values = provider.FormData.GetValues(key);
                        if (values != null)
                            foreach (var val in values)
                            {
                                if (string.Equals(key, "Share", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.Share = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "LoginUserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.LoginUserId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "FromUserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.FromUserId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "ContentType", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        ContentType = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "ContentId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.ContentId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "CreatedOn", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.CreatedOn = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "FromCommuniy", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.FromCommunity = Convert.ToBoolean(val);
                                }
                                break;
                            }
                    }

                    if (webposter.LoginUserId > 0)
                    {
                        if (webposter.Share == 0)
                        {
                            if (provider.FileData.Count != 0)
                            {
                                if (ContentType == "Image")
                                {
                                    //webposterPic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + webposter.LoginUserId + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                                    webposterPic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + webposter.LoginUserId + ".png";
                                    finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                                    img = System.Drawing.Image.FromFile(finfo.FullName);
                                    var converter = new System.Drawing.ImageConverter();
                                    b = (byte[])converter.ConvertTo(img, typeof(byte[]));
                                    webposter.WebposterImg = webposterPic;
                                    DateTime dt = DateTime.UtcNow;
                                    //DateTime dt = Convert.ToDateTime(webposter.CreatedOn);
                                    int pictureId = Convert.ToInt32(new PictureRepository().SaveUserPicture(webposter.LoginUserId, webposterPic, dt, webposter.FromCommunity));

                                    if (pictureId > 0)
                                    {
                                        //----Image upload-----
                                        Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, webposterPic), img.Width, img.Height);
                                        Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, "Thumb_" + webposterPic), 100, 100);
                                        img.Dispose();
                                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                                        strmsg = "1";
                                        //----End Image upload-----
                                    }
                                    else
                                        strmsg = "0";
                                }
                                else if (ContentType == "Video")
                                {
                                    webposterVideo = Helpers.HelperFunctions.CreateUniqueFileName() + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                                    webposter.WebposterVideo = webposterVideo;
                                    DateTime dt = DateTime.UtcNow;
                                    int VideoId = Convert.ToInt32(new VideoRepository().SaveUserVideo(webposter.LoginUserId, webposterVideo, dt, webposter.FromCommunity));
                                    if (VideoId > 0)
                                    {
                                        //----video upload-----
                                        finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                                        System.IO.File.Move(finfo.FullName, System.IO.Path.Combine(root, webposterVideo));
                                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                                        strmsg = "1";
                                        //----End video upload-----
                                    }
                                    else
                                        strmsg = "0";
                                }
                            }
                        }
                        else
                        {
                            if (ContentType == "Image")
                            {
                                Pro_PictureShareMaster objPictureShare = new Pro_PictureShareMaster();
                                objPictureShare.UserId = webposter.LoginUserId;
                                objPictureShare.PictureId = webposter.ContentId;
                                objPictureShare.CreatedOn = DateTime.UtcNow.ToString();
                                objPictureShare.ShareId = webposter.FromUserId;
                                int pictureShareId = Convert.ToInt32(new PictureShareRepository().SaveSharePicture(objPictureShare));
                                if (pictureShareId > 0)
                                    strmsg = "1";
                                else
                                    strmsg = "0";
                            }
                            else if (ContentType == "Video")
                            {
                                Pro_VideoShareMaster objVideoShare = new Pro_VideoShareMaster();
                                objVideoShare.UserId = webposter.LoginUserId;
                                objVideoShare.VideoId = webposter.ContentId;
                                objVideoShare.CreatedOn = DateTime.UtcNow.ToString();
                                objVideoShare.ShareId = webposter.FromUserId;
                                int VideoShareId = Convert.ToInt32(new VideoShareRepository().SaveShareVideo(objVideoShare));
                                if (VideoShareId > 0)
                                    strmsg = "1";
                                else
                                    strmsg = "0";
                            }
                        }
                    }
                    return ServiceHelper.GetServiceJson(ServiceHelper.JsonType.ResultMessage, StatusConstants.Ok, strmsg);
                }
            );
            return task;
        }

        [HttpPost]
        [ActionName("AddChatToWebPoster1")]
        public dynamic AddChatToWebPoster1(Pro_WebPoster objWebPoster)
        {
            string msg = string.Empty;
            bool IsSuccess;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();


            if (objWebPoster.Share == 0)
            {
                long offset = Convert.ToInt64(objWebPoster.Offset);
                string path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["WebPosterUrl"]);
                if (objWebPoster.ContentType == "Image")
                    objWebPoster.ChatImgName = objWebPoster.FileName;
                else
                    objWebPoster.ChatVideoName = objWebPoster.FileName;
                if (objWebPoster.IsUploadingEnd == true)
                {
                    new Helpers.HelperFunctions().UploadFile(objWebPoster.FileName, objWebPoster.buffer, offset, path);
                    IsSuccess = false;
                }
                else
                {
                    IsSuccess = new Helpers.HelperFunctions().UploadFile(objWebPoster.FileName, objWebPoster.buffer, offset, path);
                    dicto.Add("Success", IsSuccess);
                }

                if (IsSuccess == false)
                {
                    Pro_webPosterChat objchat = new Pro_webPosterChat();
                    objchat.FromId = objWebPoster.LoginUserId;
                    objchat.ToId = objWebPoster.FromUserId;
                    objchat.GroupId = 0;
                    objchat.ChatOn = objWebPoster.CreatedOn;
                    if (objWebPoster.ContentType == "Image")
                    {
                        objchat.ContentType = "ChatImage";
                        objchat.Content = objWebPoster.ChatImgName;
                        //--------------Thumb image------------------------------------
                        if (objWebPoster.ContentType == "Image")
                            Helpers.HelperFunctions.SaveThumbImage(path + objWebPoster.FileName, 100, 100, "Thumb_");
                        //--------------End Thumb image--------------------------------
                    }
                    else if (objWebPoster.ContentType == "Video")
                    {
                        objchat.ContentType = "ChatVideo";
                        objchat.Content = objWebPoster.ChatVideoName;
                    }
                    else
                    {
                        objchat.ContentType = "ChatText";
                        objchat.Content = objWebPoster.TextMsg;
                    }

                    int webPosterId = Convert.ToInt32(new WebPosterChatRepository().SavewebPosterChat(objchat));
                    if (webPosterId > 0)
                    {
                        dicto.Add("Status", Convert.ToBoolean(1));
                    }
                    else
                    {
                        if (File.Exists(path + "/" + objWebPoster.FileName))
                        {
                            DeleteImageVideo(path + "/" + objWebPoster.FileName);
                            if (objchat.ContentType == "ChatImage")
                                DeleteImageVideo(path + "/" + "Thumb_" + objWebPoster.FileName);
                        }
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }

                }
            }
            else
            {
                Pro_WebPosterChatShare chatshare = new Pro_WebPosterChatShare();
                chatshare.UserId = objWebPoster.LoginUserId;
                chatshare.WPChatId = objWebPoster.ContentId;
                chatshare.ShareId = objWebPoster.FromUserId;
                chatshare.CreatedOn = objWebPoster.CreatedOn;
                int ChatId = Convert.ToInt32(new WebPosterChatShareRepository().SaveShareChat(chatshare));
                if (ChatId > 0)
                {
                    dicto.Add("Status", Convert.ToBoolean(1));
                }
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("AddChatToWebPoster")]
        public System.Threading.Tasks.Task<Dictionary<string, dynamic>> AddChatToWebPoster()
        {
            HttpRequestMessage request = Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            var webposter = new Pro_WebPoster();
            string strmsg = string.Empty;
            string ContentType = string.Empty;
            string strChatContent = string.Empty;
            var root = HttpContext.Current.Server.MapPath("~/Uploads/WebPoster");
            var provider = new MultipartFormDataStreamProvider(root);

            Image img = null;
            byte[] b = null;
            System.IO.FileInfo finfo = null;
            var webposterPic = "";
            var webposterVideo = "";

            var task = request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(o =>
                {
                    foreach (var key in provider.FormData.AllKeys)
                    {
                        var values = provider.FormData.GetValues(key);
                        if (values != null)
                            foreach (var val in values)
                            {
                                if (string.Equals(key, "Share", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.Share = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "LoginUserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.LoginUserId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "FromUserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.FromUserId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "ContentType", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        ContentType = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "ContentId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.ContentId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "TextMsg", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        strChatContent = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "CreatedOn", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.CreatedOn = Convert.ToString(val);
                                }
                                break;
                            }
                    }

                    if (webposter.LoginUserId > 0)
                    {
                        if (webposter.Share == 0)
                        {
                            Pro_webPosterChat objchat = new Pro_webPosterChat();
                            objchat.FromId = webposter.LoginUserId;
                            objchat.ToId = webposter.FromUserId;
                            objchat.GroupId = 0;
                            objchat.ChatOn = DateTime.UtcNow.ToString();
                            if (provider.FileData.Count != 0)
                            {
                                if (ContentType == "Image")
                                {
                                    //webposterPic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + webposter.LoginUserId + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                                    webposterPic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + webposter.LoginUserId + ".png";
                                    finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                                    img = System.Drawing.Image.FromFile(finfo.FullName);
                                    var converter = new System.Drawing.ImageConverter();
                                    b = (byte[])converter.ConvertTo(img, typeof(byte[]));
                                    //DateTime dt = Convert.ToDateTime(webposter.CreatedOn);
                                    objchat.ContentType = "ChatImage";
                                    objchat.Content = webposterPic;
                                    int pictureId = Convert.ToInt32(new WebPosterChatRepository().SavewebPosterChat(objchat));

                                    if (pictureId > 0)
                                    {
                                        //----Image upload-----
                                        Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, webposterPic), img.Width, img.Height);
                                        Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, "Thumb_" + webposterPic), 100, 100);
                                        img.Dispose();
                                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                                        strmsg = "1";
                                        //----End Image upload-----
                                    }
                                    else
                                        strmsg = "0";
                                }
                                else if (ContentType == "Video")
                                {
                                    webposterVideo = Helpers.HelperFunctions.CreateUniqueFileName() + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                                    DateTime dt = DateTime.UtcNow;
                                    objchat.ContentType = "ChatVideo";
                                    objchat.Content = webposterVideo;
                                    int VideoId = Convert.ToInt32(new WebPosterChatRepository().SavewebPosterChat(objchat));
                                    if (VideoId > 0)
                                    {
                                        //----video upload-----
                                        finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                                        System.IO.File.Move(finfo.FullName, System.IO.Path.Combine(root, webposterVideo));
                                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                                        strmsg = "1";
                                        //----End video upload-----
                                    }
                                    else
                                        strmsg = "0";
                                }
                            }
                            if (ContentType == "TextMsg")
                            {
                                objchat.ContentType = "ChatText";
                                objchat.Content = strChatContent;
                                int ChatId = Convert.ToInt32(new WebPosterChatRepository().SavewebPosterChat(objchat));
                                if (ChatId > 0)
                                {
                                    strmsg = "1";
                                }
                                else
                                    strmsg = "0";
                            }
                        }
                        else
                        {
                            Pro_WebPosterChatShare chatshare = new Pro_WebPosterChatShare();
                            chatshare.UserId = webposter.LoginUserId;
                            chatshare.WPChatId = webposter.ContentId;
                            chatshare.ShareId = webposter.FromUserId;
                            chatshare.CreatedOn = DateTime.UtcNow.ToString();
                            int ChatId = Convert.ToInt32(new WebPosterChatShareRepository().SaveShareChat(chatshare));
                            if (ChatId > 0)
                            {
                                strmsg = "1";
                            }
                            else
                                strmsg = "0";
                        }
                    }
                    return ServiceHelper.GetServiceJson(ServiceHelper.JsonType.ResultMessage, StatusConstants.Ok, strmsg);
                }
            );
            return task;
        }

        [HttpPost]
        [ActionName("GetDatesForWebposter")]
        public dynamic GetDatesForWebposter(Pro_WebPoster objPro_WebPoster)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var DateList = new WebPosterRepository().GetDatesForWebPoster(objPro_WebPoster);

            if (DateList.Count > 0)
            {
                if(DateList[0] == "2")
                    dicto.Add("Status", Convert.ToInt32(DateList[0]));
                else
                    dicto.Add("Result", DateList);
            }
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetDetailsForWebPoster")]
        public dynamic GetDetailsForWebPoster(Pro_WebPoster objProWebPoster)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var DateList = new WebPosterRepository().GetDetailsForWebPosterByDate(objProWebPoster);

            if (DateList.Count > 0)
                dicto.Add("Result",DateList);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("WelcomeHome")]
        public dynamic WelcomeHome(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var CountDetail = new UserRepository().InsertLatLongAndUserStatus(user);

            if (user.UserId > 0)
                dicto.Add("Result",CountDetail);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }


        [HttpPost]
        [ActionName("UserStatus")]
        public dynamic UserStatus(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var CountDetail = new UserRepository().UserStatus(user);

            if (CountDetail > 0)
                 dicto.Add("Result",CountDetail);
            else
                 dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("UserPrivacySetting")] //for on and of
        public dynamic UserPrivacySetting(Pro_UserPrivacySetting user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserDetail = new UserRepository().UpdatePrivacySetting(user);

            if (UserDetail > 0)
                dicto.Add("Status", Convert.ToBoolean(1));
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }
        #endregion


        #region News

        [HttpPost]
        [ActionName("GetNewsCount")]
        public dynamic GetNewsCount(Pro_News objNews)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var newsCount = new NewsRepository().GetNewsCount(objNews);

            if (newsCount > 0)
                dicto.Add("Result",newsCount);
            else
                 dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }


        [HttpPost]
        [ActionName("GetLatestNewsList")]
        /* UserID,ViewOn*/
        public dynamic GetLatestNewsList(Pro_News objProNews)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var DateList = new NewsRepository().GetLatestNewsList(objProNews);

            if (DateList.Count > 0)
                dicto.Add("Result", DateList);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("SetContentSeenByUser")]
        /* UserID,ViewOn*/
        public dynamic SetContentSeenByUser(Pro_News objProNews)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            int NewsId = Convert.ToInt32(new NewsRepository().SetContentSeenByUser(objProNews));

            if (NewsId > 0)
                dicto.Add("Status", Convert.ToBoolean(1));
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        //[HttpPost]
        //[ActionName("FriendScreen")]
        //public dynamic FriendScreen(Pro_ChatHistoryMaster objProChat)
        //{
        //    Dictionary<string, dynamic> dicto;
        //    var DateList = new ChatHistoryRepository().GetDetailForFriendScreen(objProChat);

        //    if (DateList.Count > 0)
        //        dicto = ServiceHelper.GetServiceJson(ServiceHelper.JsonType.Data, StatusConstants.Ok, DateList, "", true);
        //    else
        //    {
        //        dicto = new Dictionary<string, dynamic>();
        //        dicto.Add("Result", "Records not found");
        //        if (Convert.ToString(objProChat.ChatOn) == "1/1/1900 12:00:00 AM")
        //            dicto.Add("Date", new UserRepository().Getdate());
        //    }
        //    return dicto;
        //}

        [HttpPost]
        [ActionName("Truncate")]
        public dynamic Truncate()
        {
            Dictionary<string, dynamic> dicto;
            var detail = new UserRepository().Truncate();

            if (detail)
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "Truncated data Successfully");
            }
            else
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "Truncate fail");
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("SearchUserByName")]
        public dynamic SearchUserByName(Pro_UserMaster User)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var DateList = new UserRepository().GetUserBySerachName(User);

            if (DateList.Count > 0)
                dicto.Add("Result", DateList);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("AddAsFriend")]
        public dynamic AddAsFriend(Pro_UserContact User)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var Userid = Convert.ToInt32(new UserContactRepository().AddAsFriend(User));
            if (Userid > 0)
            {
                dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("AuthenticateUserForRestore")]
        public dynamic AuthenticateUserForRestore(Pro_UserMaster User)
        {
            Dictionary<string, dynamic> dicto;
            var detail = new UserRepository().RestoreUser(User);

            if (detail == -1)
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "ContactNo does not exists");
            }
            else if (detail == -2)
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "Email does not exists");
            }
            else if (detail == 0)
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "Email and contact does not exists");
            }
            else
            {
                Random rnd = new Random();
                string code = rnd.Next(1000, 10000).ToString();
                if (code.Length == 3)
                    code = code + "0";
                else if (code.Length == 2)
                    code = code + "00";
                dicto = new Dictionary<string, dynamic>();


                //-------------------Send Email with varfication code--------------
                bool EmailStatus = EmailHelper.SendEmailForVarificationCode(User.EmailId, code, User.ContactNo);
                if (EmailStatus == true)
                {
                    dicto.Add("code", code);
                   // dicto.Add("Status", Convert.ToBoolean(1));
                }
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("RestoreUser")]
        public dynamic RestoreUser(Pro_UserMaster User)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var UserId = new UserRepository().RestoreUser(User);
            if (UserId > 0)
            {
                var UserProfile = new UserRepository().GetUserProfile(UserId);
                var FriendList = new UserContactRepository().GetContactList(UserId);
                if (UserProfile.UserId > 0)
                    dicto.Add("UserDetail", UserProfile);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
                //dicto.Add("RegistrationDate", new UserRepository().Getdate());

                if(FriendList.Count > 0)
                    dicto.Add("FriendList", FriendList);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));

                return dicto;
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("checkForContact")]
        public dynamic checkForContact(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var UserDetails = new ContactDetailsRepository().checkForContact(user.UserId, user.ContactNo);
            if (UserDetails.UserId > 0)
               dicto.Add("Result",UserDetails);
            else
                dicto.Add("Status", "0");
            return dicto;
        }

        [HttpPost]
        [ActionName("CustomPrivacySetting")]
        public dynamic CustomPrivacySetting(Pro_PrivacySetting user)
        {
            string UserSetting = string.Empty;
            string GroupSetting = string.Empty;
            int i = 0;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();

            Pro_UserPrivacySetting objuser = new Pro_UserPrivacySetting();
            objuser.UserId = user.UserId;
            objuser.PrivacySetting = 2;
            var UserDetail = new UserRepository().UpdatePrivacySetting(objuser);
            if (UserDetail > 0)
            {
                UserSetting = Convert.ToString(user.UserSettingArray);
                GroupSetting = Convert.ToString(user.GroupSettingArray);

                //---User Setting array------------
                JavaScriptSerializer jss = new JavaScriptSerializer();
                List<Pro_UserPrivacySetting_Api> UserSettingList = jss.Deserialize<List<Pro_UserPrivacySetting_Api>>(UserSetting);
                //---End--------------------------

                //---User Setting array------------
                JavaScriptSerializer jss1 = new JavaScriptSerializer();
                List<Pro_GroupPrivacySetting_Api> GroupSettingList = jss1.Deserialize<List<Pro_GroupPrivacySetting_Api>>(GroupSetting);
                //---End--------------------------

                string result = new PrivacySettingRepository().InsertPrivacySetting(UserSettingList, GroupSettingList, user.UserId);
                if (result == "1")
                {
                    dicto.Add("Status", Convert.ToBoolean(1));
                }
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }
        #endregion

        [HttpPost]
        [ActionName("UploadVideo")]
        public dynamic Upload(Pro_VideoMaster_Api video)
        {
            Dictionary<string, dynamic> dicto;
            // byte[] b = Encoding.ASCII.GetBytes(video.buffer);
            long offset = Convert.ToInt64(video.Offset);
            string path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["upload_path"]);
            var IsSuccess = new Helpers.HelperFunctions().UploadFile(video.FileName, video.buffer, offset, path);

            dicto = new Dictionary<string, dynamic>();
            dicto.Add("Result", IsSuccess);
            dicto.Add("Message", (IsSuccess == true ? "Success" : "Failure"));

            return dicto;

        }

        [HttpPost]
        [ActionName("InsertChatWithImageOrVideo1")]
        public dynamic InsertChatWithImageOrVideo1(Pro_ChatHistoryMaster chat)
        {
            string msg = string.Empty;
            bool IsSuccess;
            int chatId = 0;
            Pro_ChatHistoryMaster objchat = new Pro_ChatHistoryMaster();
            Pro_ChatDateDetail Chat = new Pro_ChatDateDetail();
            Pro_GroupChatDateDetail ChatDetail = new Pro_GroupChatDateDetail();
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            long offset = Convert.ToInt64(chat.Offset);
            string path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["UploadChatImageVideo"]);

            if (chat.Upload == "Image")
                chat.ImagePath = chat.FileName;
            else
                chat.VideoPath = chat.FileName;
            if (chat.IsUploadingEnd == true)
            {
                new Helpers.HelperFunctions().UploadFile(chat.FileName, chat.buffer, offset, path);
                IsSuccess = false;
            }
            else
            {
                IsSuccess = new Helpers.HelperFunctions().UploadFile(chat.FileName, chat.buffer, offset, path);
                dicto.Add("Success", IsSuccess);
            }

            if (IsSuccess == false)
            {
                //--------------Thumb image------------------------------------
                if (chat.Upload == "Image")
                    Helpers.HelperFunctions.SaveThumbImage(path + chat.FileName, 100, 100, "Thumb_");
                //--------------End Thumb image--------------------------------
                //--------------Insert Process----------------------------------
                if (chat.GroupId != 0)
                {
                    ChatDetail = new ChatHistoryRepository().InsertGroupChat(chat);
                    if (ChatDetail.Status == true)
                        dicto.Add("Result", ChatDetail);
                    else
                    {
                        if (File.Exists(path + "/" + chat.FileName))
                            DeleteImageVideo(path + "/" + chat.FileName);
                        if (chat.Upload == "Image")
                            DeleteImageVideo(path + "/" + "Thumb_" + chat.FileName);
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }
                }
                else
                {
                    Chat = new ChatHistoryRepository().SaveChat(chat);
                    //chatId = Convert.ToInt32(new ChatHistoryRepository().SaveChat(chathistory));
                    if (Chat.ServerID > 0)
                    {
                        dicto.Add("Result", Chat);
                        //dicto.Add("Status", Convert.ToBoolean(1));
                    }
                    else
                    {
                        if (File.Exists(path + "/" + chat.FileName))
                        {
                            DeleteImageVideo(path + "/" + chat.FileName);
                            if (chat.Upload == "Image")
                                DeleteImageVideo(path + "/" + "Thumb_" + chat.FileName);
                        }
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }
                }
            }
            //--------------End Insert Process-------------
            return dicto;
        }

        //[HttpPost]
        //[ActionName("UploadVideo1")]
        //public string UploadVideo1(Pro_VideoMaster_Api1 video)
        //{
        //    //Dictionary<string, dynamic> dicto;
        //    string FilePath=video.File;
        //    int Offset = 0; // starting offset.
        //    int ChunkSize = 65536;

        //    byte[] Buffer = new byte[ChunkSize];
        //    //opening the file for read.
        //    FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
        //    //creating the ServiceSoapClient which will allow to connect to the service.
        //    //WSservice.ServiceSoapClient soap_client = new WSservice.ServiceSoapClient();
        //    try
        //    {
        //        long FileSize = new FileInfo(FilePath).Length; // File size of file being uploaded.
        //        // reading the file.
        //        fs.Position = Offset;
        //        int BytesRead = 0;

        //        while (Offset != FileSize) // continue uploading the file chunks until offset = file size.
        //        {
        //            BytesRead = fs.Read(Buffer, 0, ChunkSize); // read the next chunk
        //            // (if it exists) into the buffer.
        //            // the while loop will terminate if there is nothing left to read
        //            // check if this is the last chunk and resize the buffer as needed
        //            // to avoid sending a mostly empty buffer
        //            // (could be 10Mb of 000000000000s in a large chunk)
        //            if (BytesRead != Buffer.Length)
        //            {
        //                ChunkSize = BytesRead;
        //                byte[] TrimmedBuffer = new byte[BytesRead];
        //                Array.Copy(Buffer, TrimmedBuffer, BytesRead);
        //                Buffer = TrimmedBuffer; // the trimmed buffer should become the new 'buffer'
        //            }
        //            // send this chunk to the server. it is sent as a byte[] parameter,
        //            // but the client and server have been configured to encode byte[] using MTOM.
        //            bool ChunkAppened = new VideoRepository().UploadFile(Path.GetFileName(FilePath), Buffer, Offset);
        //            if (!ChunkAppened)
        //            {
        //                break;
        //            }

        //            // Offset is only updated AFTER a successful send of the bytes.
        //            Offset += BytesRead; // save the offset position for resume
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //    }
        //    finally
        //    {
        //        fs.Close();
        //    }

        //    return "Success";

        //}

        [HttpPost]
        [ActionName("InsertComment")] //for on and of
        public dynamic InsertComment(Pro_CommentMaster Comment)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var CommentId = new CommentMasterRepository().SaveComment(Comment);

            if (Convert.ToInt32(CommentId) > 0)
            {
               // dicto.Add("CommentId", Convert.ToInt32(CommentId));
                dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("InsertLike")] //for on and of
        public dynamic InsertLike(Pro_LikeMaster Like)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var LikeId = new LikeMasterRepository().SaveLike(Like);

            if (Convert.ToInt32(LikeId) > 0)
            {
                //dicto.Add("LikeId", Convert.ToInt32(LikeId));
                dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("DeleteComment")] //for on and of
        public dynamic DeleteComment(Pro_CommentMaster Comment)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var CommentId = new CommentMasterRepository().DeleteComment(Comment.CommentId);

            if (Convert.ToInt32(CommentId) > 0)
            {
                dicto.Add("CommentId", Convert.ToInt32(CommentId));
                //dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("DeleteLike")] //for on and of
        public dynamic DeleteLike(Pro_LikeMaster Like)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var LikeId = new LikeMasterRepository().DeleteLike(Like.LikeId);

            if (Convert.ToInt32(LikeId) > 0)
            {
                dicto.Add("LikeId", Convert.ToInt32(LikeId));
                //dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }


        [HttpPost]
        [ActionName("GetComment")] //for on and of
        public dynamic GetComment(Pro_CommentMaster Comment)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var CommentList = new CommentMasterRepository().GetComment(Comment);

            if (CommentList.Count > 0)
                dicto.Add("Result", CommentList);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("GetLikeCount")] //for on and of
        public dynamic GetLikeCount(Pro_LikeMaster Like)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var LikeCount = new LikeMasterRepository().GetLikeCount(Like);

            if (LikeCount > 0)
                dicto.Add("LikeCount", LikeCount);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetRecentMsg")]
        public dynamic GetRecentMsg(Pro_ChatHistoryMaster Chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>(); ;
            List<Pro_FriendScreen_Api> chats = new ChatHistoryRepository().GetRecentMsg(Chat);
            if (chats.Count > 0)
            {
                dicto.Add("Result", chats);
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        //-------Add by Nirmal 7-01-2013-------
        [HttpPost]
        [ActionName("GetHighlightedContent")] //for send total like count and other information
        public dynamic GetLikeCount(Pro_LikesMaster objlikes)
        {
            const int pageSize = 10;
            int count = 0;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var TotalLikecount = new LikeMasterRepository().GetAllLikesCount(objlikes.RecordIndex, objlikes.ContentType);
            if (TotalLikecount.Count > 0)
            {
                dicto.Add("Result", TotalLikecount);
                if (TotalLikecount.Count < pageSize || ((objlikes.RecordIndex + pageSize) == count))
                {
                    dicto.Add("Count", TotalLikecount.Count);
                    dicto.Add("Next", false);
                }
                else
                {
                    dicto.Add("Count", TotalLikecount.Count);
                    dicto.Add("Next", true);
                }
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("GetHighlightedComments")]
        public dynamic GetComments(Pro_CommentsMaster objcomments)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var TotalComments = new LikeMasterRepository().GetAllComments(objcomments.ContentId, objcomments.ContentType);
            if (TotalComments.Count > 0)
            {
                dicto.Add("Result", TotalComments);
                dicto.Add("Count", TotalComments.Count);
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        //------------End-----------------

        [HttpPost]
        [ActionName("UpdateTypingStatus")]
        public dynamic UpdateTypingStatus(Pro_ChatHistoryMaster chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var Res = new ChatHistoryRepository().UpdateTypingStatus(chat);
            if (Convert.ToInt32(Res) > 0)
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }
    }
}
        [HttpPost]
        [ActionName("UpdateTypingStatus")]
        public dynamic UpdateTypingStatus(Pro_ChatHistoryMaster chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var Res = new ChatHistoryRepository().UpdateTypingStatus(chat);
            if (Convert.ToInt32(Res) > 0)
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }
    }
}