Tuesday, 28 February 2017


Facebook Sharing in ASP .Net

Code-Behind

using Facebook;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Http;



namespace FacebookDev
{
    public partial class FacebookSharing : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
               // Authorization();
            }
        }
        protected void Authorization()
        {
            string app_id = "982579805207954";
            string app_sceret = "d8d9b44d566ef09132a054b119b7821d";
            string scope = "publish_actions,manage_pages";
            if (Request["code"] == null)
            {
                Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
                  app_id, Request.Url.AbsoluteUri, scope));
            }
            else
            {
                Dictionary<string, string> tokens = new Dictionary<string, string>();
                string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
                   app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_sceret);

             
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
           
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader responseReader = null;
                    string responseData = "";

                    responseReader = new StreamReader(response.GetResponseStream());

                    responseData = responseReader.ReadToEnd();
                 
                    foreach (string token in responseData.Split('&'))
                    {
                        //meh.aspx?token1=aa&token2=bb&...
                        tokens.Add(token.Substring(0, token.IndexOf("=")),
                            token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
                    }
                }
                string access_token = tokens["access_token"];
                var client = new FacebookClient(access_token);
                client.PostTaskAsync("/me/feed", new { message = txtShow.Text });
            }
        }

        protected void share_button_Click(object sender, EventArgs e)
        {
            Authorization();
        }
    }
}

========================================================================
Design Page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FacebookSharing.aspx.cs" Inherits="FacebookDev.FacebookSharing" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script>
    window.fbAsyncInit = function () {
        FB.init({
            appId: '1492479487428964', status: true, cookie: true,
            xfbml: true
        });
    };
    (function () {
        var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol +
        'https://connect.facebook.net/en_US/all.js';
        document.getElementById('fb-root').appendChild(e);
    }());
</script>
<script type="text/javascript">
    $(document).ready(function () {
        //$('#share_button').click(function (e) {
            e.preventDefault();
            FB.ui(
{
    method: 'feed',
   // name: TestVar,
    link: 'http://localhost:1536/FacebookSharing.aspx',
    //picture: 'http://www.c-sharpcorner.com/UploadFile/AuthorImage/raj1979.gif',
    caption: 'This article demonstrates how to use the jQuery dialog feature in ASP.Net.',
    description: 'First of all make a new website in ASP.Net and add a new stylesheet and add .js files and put images in the images folder and make a reference to the page.',
    //message: 'hello raj message'
});
        });
    //});
</script>
<body>
    <script>
        window.fbAsyncInit = function () {
            FB.init({
                appId: '1492479487428964',
                xfbml: true,
                version: 'v2.8'
            });
            FB.AppEvents.logPageView();
        };

        (function (d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) { return; }
            js = d.createElement(s); js.id = id;
            js.src = "https://connect.facebook.net/en_US/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));
    </script>
    <form id="form1" runat="server">

        <div align="center">
            <div id="fb-root">
            </div>
            <div>
                <asp:TextBox ID="txtShow" runat="server" TextMode="MultiLine" Height="60px"></asp:TextBox>
            </div>
            <div></div>
            <div>
                <asp:Button runat="server" ID="share_button" Text="Share" OnClick="share_button_Click" />
            </div>
        </div>
    </form>
</body>
</html>



Tuesday, 21 February 2017

Check Duplicate

protected bool ChkDuplicate()
        {
            bool noduplicate = true;
            for (int i = 0; i < itemGrid.Rows.Count; i++)
            {
                if (itemGrid.Rows[i].Cells[2].Text == txtItem_Name.Text)
                {
                    Response.Write("<script>alert('Exist Data!')</script>");
                    return false;
                }
            }
            return noduplicate;
        }



Catch Exception

catch (Exception ex)
            {
                Response.Write("<script>alert('" + ex.ToString() + "');</script>");
            }
Resolver


using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Web.Http.Dependencies;

namespace WebApiAzure.Resolver
{
    public class UnityResolver : IDependencyResolver
    {
        protected IUnityContainer container;
        public UnityResolver(IUnityContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }
            this.container = container;
        }

        public object GetService(Type serviceType)
        {
            try
            {
                return container.Resolve(serviceType);
            }
            catch (ResolutionFailedException)
            {
                return null;
            }
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            try
            {
                return container.ResolveAll(serviceType);
            }
            catch (ResolutionFailedException)
            {
                return new List<object>();
            }
        }

        public IDependencyScope BeginScope()
        {
            var child = container.CreateChildContainer();
            return new UnityResolver(child);
        }

        public void Dispose()
        {
            container.Dispose();
        }
    }
}
Service

using BusinessEntities;
using DataModel.UnitOfWork;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace BusinessServices
{
    public class EducationCategoryService : IEducationCategoryService
    {
        private readonly UnitOfWork _unitOfWork;

        /// Public constructor.
        public EducationCategoryService()
        {
            _unitOfWork = new UnitOfWork();
        }

        /// Fetches EducationCategory Details by ID
        public EducationCategory GetEducationCategoryById(int EducationCategory_Id)
        {
            var educationcategory = _unitOfWork.EducationCategoryRepository.GetByID(EducationCategory_Id);
            if (educationcategory != null)
            {
                //Mapper.CreateMap<City, City>();
                //var cityModel = Mapper.Map<City, City>(city);
                //return cityModel;
                return educationcategory;
            }
            return null;
        }

        /// Fetches all the EducationCategory.
        public IEnumerable<EducationCategory> GetAllEducationCategory()
        {
            var educationcategory = _unitOfWork.EducationCategoryRepository.GetAll().ToList();
            if (educationcategory.Any())
            {
                //Mapper.CreateMap<City, City>();
                //var productsModel = Mapper.Map<List<City>, List<City>>(citys);
                //return productsModel;
                return educationcategory;
            }
            return null;
        }

        /// Creates a EducationCategory
        public int CreateEducationCategory(EducationCategory educationCategoryEntity)
        {
            using (var scope = new TransactionScope())
            {
                var educationcategory = new EducationCategory
                {
                    EducationCategory_Id = educationCategoryEntity.EducationCategory_Id,
                    EducationCategory_Code = educationCategoryEntity.EducationCategory_Code,
                    EducationCategory_Name = educationCategoryEntity.EducationCategory_Name,
                    EducationCategory_Description = educationCategoryEntity.EducationCategory_Description,
                    InsertedBy = educationCategoryEntity.InsertedBy,
                    InsertedOn = educationCategoryEntity.InsertedOn,
                    IsActive = educationCategoryEntity.IsActive,
                    IsDelete = educationCategoryEntity.IsDelete

                };
                _unitOfWork.EducationCategoryRepository.Insert(educationcategory);
                _unitOfWork.Save();
                scope.Complete();
                return educationcategory.EducationCategory_Id;
            }
        }

        /// Updates a EducationCategory
        public bool UpdateEducationCategory(int EducationCategory_Id, EducationCategory educationcategoryEntity)
        {
            var success = false;
            if (educationcategoryEntity != null)
            {
                using (var scope = new TransactionScope())
                {
                    var educationcategory = _unitOfWork.EducationCategoryRepository.GetByID(EducationCategory_Id);
                    if (educationcategory != null)
                    {
                        educationcategory.EducationCategory_Id = EducationCategory_Id;
                        educationcategory.EducationCategory_Code = educationcategoryEntity.EducationCategory_Code;
                        educationcategory.EducationCategory_Name = educationcategoryEntity.EducationCategory_Name;
                        educationcategory.EducationCategory_Description = educationcategoryEntity.EducationCategory_Description;
                        educationcategory.LastModifiedBy = educationcategoryEntity.LastModifiedBy;
                        educationcategory.LastModifiedOn = educationcategoryEntity.LastModifiedOn;
                        educationcategory.IsActive = educationcategoryEntity.IsActive;
                        educationcategory.IsDelete = educationcategoryEntity.IsDelete;
                        _unitOfWork.EducationCategoryRepository.Update(educationcategory);
                        _unitOfWork.Save();
                        scope.Complete();
                        success = true;
                    }
                }
            }
            return success;
        }

        /// Deletes a particular EducationCategory
        public bool DeleteEducationCategory(int EducationCategory_Id, EducationCategory educationcategoryEntity)
        {
            var success = false;
            if (EducationCategory_Id > 0)
            {
                using (var scope = new TransactionScope())
                {
                    var educationcategory = _unitOfWork.EducationCategoryRepository.GetByID(EducationCategory_Id);
                    if (educationcategory != null)
                    {
                        educationcategory.EducationCategory_Id = EducationCategory_Id;
                        educationcategory.LastModifiedOn = educationcategoryEntity.LastModifiedOn;
                        educationcategory.LastModifiedBy = educationcategoryEntity.LastModifiedBy;
                        educationcategory.IsActive = educationcategoryEntity.IsActive;
                        educationcategory.IsDelete = educationcategoryEntity.IsDelete;
                        _unitOfWork.EducationCategoryRepository.Update(educationcategory);
                        _unitOfWork.Save();
                        scope.Complete();
                        success = true;
                    }
                }
            }
            return success;
        }
    }  
}

Interface

using BusinessEntities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BusinessServices
{
    public interface IEducationCategoryService
    {
        EducationCategory GetEducationCategoryById(int EducationCategory_Id);
        //IEnumerable<City> GetCityById(int CityId);
        IEnumerable<EducationCategory> GetAllEducationCategory();
        int CreateEducationCategory(EducationCategory educationCategoryEntity);
        bool UpdateEducationCategory(int EducationCategory_Id, EducationCategory educationCategoryEntity);
        bool DeleteEducationCategory(int EducationCategory_Id, EducationCategory educationCategoryEntity);
    }
}

Unit of Work

#region Using Namespaces...

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Data.Entity.Validation;
using DataModel.GenericRepository;
using BusinessEntities;

#endregion

namespace DataModel.UnitOfWork
{
    /// <summary>
    /// Unit of Work class responsible for DB transactions
    /// </summary>
    public class UnitOfWork : IDisposable
    {
        #region Private member variables...

        private HrmsEntities _context = null;
        private GenericRepository<City> _cityRepository;
        private GenericRepository<EducationCategory> _educationCatagoryRepository;
        private GenericRepository<BoardUniversity> _boardUniversityRepository;
        private GenericRepository<Skill> _SkillRepository;
        private GenericRepository<SkillLevel> _SkillLevelRepository;
        private GenericRepository<SkillGroup> _SkillGroupRepository;
        private GenericRepository<SkillType> _skillTypepRepository;
        private GenericRepository<KRAGroup> _kraGroupRepository;
        private GenericRepository<Qualification> _QualificationRepository;
        private GenericRepository<JobCode> _JobCodeRepository;
        private GenericRepository<Caste> _CasteRepository;
        private GenericRepository<QualificationCategory> _QualificationCategoryRepository;
        private GenericRepository<Scale> _scaleRepository;
        private GenericRepository<ScaleDtl> _scaledetailsRepository;
        //private GenericRepository<State> _stateRepository;
        private GenericRepository<Education> _educationRepository;
        private GenericRepository<EducationDetail> _educationDetailRepository;
        private GenericRepository<EarningDeductionCode> _earningDeductionCodeRepository;
        private GenericRepository<KRA> _kraRepository;
        private GenericRepository<KRAGroupDtl> _kraGroupDtlRepository;
        private GenericRepository<QualificationDimension> _QualificationDimensionRepository;
        private GenericRepository<HRMS_EmployeeProfessionalDetails> _HRMS_EmployeeProfessionalDetailsRepository;
        private GenericRepository<Grade> _GradeRepository;
        private GenericRepository<LinkScalewithGrade> _LinkScalewithGradeRepository;
        private GenericRepository<QualificationSpecialization> _QualificationSpecializationRepository;
        private GenericRepository<Certificate> _CertificateRepository;
        private GenericRepository<LeaveType> _leaveTypeRepository;
        private GenericRepository<JobType> _JobTypeRepository;
        private GenericRepository<HRMS_InterviewRound>_InterviewRoundRepository;
        private GenericRepository<HRMS_ExpenseType> _HRMS_ExpenseTypeRepository;
        private GenericRepository<HRMS_InterviewVenueFloor> _HRMS_InterviewVenueFloor;
        private GenericRepository<HRMS_InterviewVenueRoom> _HRMS_InterviewVenueRoom;
        private GenericRepository<Relationship> _relationshipRepository;
        private GenericRepository<HRMS_JobTasks> _HRMS_jobTasksRepository;
        private GenericRepository<HRMS_InterviewExpense> _HRMS_InterviewExpenseRepository;
        private GenericRepository<HRMS_InterviewVenue> _hrms_InterviewVenuRepository;
        private GenericRepository<JobFunction> _jobFunctionRepository;
        #endregion

        public UnitOfWork()
        {
            _context = new HrmsEntities();
        }

        #region Public Repository Creation properties...

        /// <summary>
        /// Get/Set Property for city repository.
        /// </summary>

        public GenericRepository<JobFunction> JobFunctionRepository
        {
            get
            {
                if (this._jobFunctionRepository == null)
                    this._jobFunctionRepository = new GenericRepository<JobFunction>(_context);
                return _jobFunctionRepository;
            }
        }

        public GenericRepository<HRMS_InterviewExpense> HRMS_InterviewExpenseRepository
        {
            get
            {
                if (this._HRMS_InterviewExpenseRepository == null)
                    this._HRMS_InterviewExpenseRepository = new GenericRepository<HRMS_InterviewExpense>(_context);
                return _HRMS_InterviewExpenseRepository;
            }
        }
        public GenericRepository<HRMS_ExpenseType> HRMS_ExpenseTypeRepository
        {
            get
            {
                if (this._HRMS_ExpenseTypeRepository == null)
                    this._HRMS_ExpenseTypeRepository = new GenericRepository<HRMS_ExpenseType>(_context);
                return _HRMS_ExpenseTypeRepository;
            }
        }

        public GenericRepository<JobCode> JobcodeRepository
        {
            get
            {
                if (this._JobCodeRepository == null)
                    this._JobCodeRepository = new GenericRepository<JobCode>(_context);
                return _JobCodeRepository;
            }
        }

        public GenericRepository<Certificate> CertificateRepository
        {
            get
            {
                if (this._CertificateRepository == null)
                    this._CertificateRepository = new GenericRepository<Certificate>(_context);
                return _CertificateRepository;
            }
        }

        public GenericRepository<City> CityRepository
        {
            get
            {
                if (this._cityRepository == null)
                    this._cityRepository = new GenericRepository<City>(_context);
                return _cityRepository;
            }
        }

        public GenericRepository<QualificationSpecialization> QualificationSpecializationRepository
        {
            get
            {
                if (this._QualificationSpecializationRepository == null)
                    this._QualificationSpecializationRepository = new GenericRepository<QualificationSpecialization>(_context);
                return _QualificationSpecializationRepository;
            }
        }

        public GenericRepository<EducationCategory> EducationCategoryRepository
        {
            get
            {
                if (this._educationCatagoryRepository == null)
                    this._educationCatagoryRepository = new GenericRepository<EducationCategory>(_context);
                return _educationCatagoryRepository;
            }
        }

        public GenericRepository<BoardUniversity> BoardUniversityRepository
        {
            get
            {
                if (this._boardUniversityRepository == null)
                    this._boardUniversityRepository = new GenericRepository<BoardUniversity>(_context);
                return _boardUniversityRepository;
            }
        }

        public GenericRepository<Skill> SkillRepository
        {
            get
            {
                if (this._SkillRepository == null)
                    this._SkillRepository = new GenericRepository<Skill>(_context);
                return _SkillRepository;
            }
        }

        public GenericRepository<SkillLevel> SkillLevelRepository
        {
            get
            {
                if (this._SkillLevelRepository == null)
                    this._SkillLevelRepository = new GenericRepository<SkillLevel>(_context);
                return _SkillLevelRepository;
            }
        }

        public GenericRepository<SkillGroup> SkillGroupRepository
        {
            get
            {
                if (this._SkillGroupRepository == null)
                    this._SkillGroupRepository = new GenericRepository<SkillGroup>(_context);
                return _SkillGroupRepository;
            }
        }

        public GenericRepository<SkillType> SkillTypeRepository
        {
            get
            {
                if (this._skillTypepRepository == null)
                    this._skillTypepRepository = new GenericRepository<SkillType>(_context);
                return _skillTypepRepository;
            }
        }

        public GenericRepository<KRAGroup> KRAGroupRepository
        {
            get
            {
                if (this._kraGroupRepository == null)
                    this._kraGroupRepository = new GenericRepository<KRAGroup>(_context);
                return _kraGroupRepository;
            }
        }

        public GenericRepository<KRAGroupDtl> KRAGroupDtlRepository
        {
            get
            {
                if (this._kraGroupDtlRepository == null)
                    this._kraGroupDtlRepository = new GenericRepository<KRAGroupDtl>(_context);
                return _kraGroupDtlRepository;
            }
        }

        public GenericRepository<KRA> KRARepository
        {
            get
            {
                if (this._kraRepository == null)
                    this._kraRepository = new GenericRepository<KRA>(_context);
                return _kraRepository;
            }
        }

        public GenericRepository<Qualification> QualificationRepository
        {
            get
            {
                if (this._QualificationRepository == null)
                    this._QualificationRepository = new GenericRepository<Qualification>(_context);
                return _QualificationRepository;
            }
        }

        public GenericRepository<Caste> CasteRepository
        {
            get
            {
                if (this._CasteRepository == null)
                    this._CasteRepository = new GenericRepository<Caste>(_context);
                return _CasteRepository;
            }
        }

        public GenericRepository<QualificationCategory> QualificationCategoryRepository
        {
            get
            {
                if (this._QualificationCategoryRepository == null)
                    this._QualificationCategoryRepository = new GenericRepository<QualificationCategory>(_context);
                return _QualificationCategoryRepository;
            }
        }

        public GenericRepository<Scale> scaleRepository
        {
            get
            {
                if (this._scaleRepository == null)
                    this._scaleRepository = new GenericRepository<Scale>(_context);
                return _scaleRepository;
            }
        }

        public GenericRepository<ScaleDtl> scaledetailsRepository
        {
            get
            {
                if (this._scaledetailsRepository == null)
                    this._scaledetailsRepository = new GenericRepository<ScaleDtl>(_context);
                return _scaledetailsRepository;
            }
        }

        public GenericRepository<Education> EducationRepository
        {
            get
            {
                if (this._educationRepository == null)
                    this._educationRepository = new GenericRepository<Education>(_context);
                return _educationRepository;
            }
        }

        public GenericRepository<EducationDetail> EducationDetailRepository
        {
            get
            {
                if (this._educationDetailRepository == null)
                    this._educationDetailRepository = new GenericRepository<EducationDetail>(_context);
                return _educationDetailRepository;
            }
        }

        public GenericRepository<EarningDeductionCode> EarningDeductionCodeRepository
        {
            get
            {
                if (this._earningDeductionCodeRepository == null)
                    this._earningDeductionCodeRepository = new GenericRepository<EarningDeductionCode>(_context);
                return _earningDeductionCodeRepository;
            }
        }

        public GenericRepository<QualificationDimension> QualificationDimensionRepository
        {
            get
            {
                if (this._QualificationDimensionRepository == null)
                    this._QualificationDimensionRepository = new GenericRepository<QualificationDimension>(_context);
                return _QualificationDimensionRepository;
            }
        }

        public GenericRepository<HRMS_EmployeeProfessionalDetails> HRMS_EmployeeProfessionalDetailsRepository
        {
            get
            {
                if (this._HRMS_EmployeeProfessionalDetailsRepository == null)
                    this._HRMS_EmployeeProfessionalDetailsRepository = new GenericRepository<HRMS_EmployeeProfessionalDetails>(_context);
                return _HRMS_EmployeeProfessionalDetailsRepository;
            }
        }

        public GenericRepository<Grade> GradeRepository
        {
            get
            {
                if (this._GradeRepository == null)
                    this._GradeRepository = new GenericRepository<Grade>(_context);
                return _GradeRepository;
            }
        }

        public GenericRepository<LinkScalewithGrade> LinkScalewithGradeRepository
        {
            get
            {
                if (this._LinkScalewithGradeRepository == null)
                    this._LinkScalewithGradeRepository = new GenericRepository<LinkScalewithGrade>(_context);
                return _LinkScalewithGradeRepository;
            }
        }

        public GenericRepository<LeaveType> LeaveTypeRepository
        {
            get
            {
                if (this._leaveTypeRepository == null)
                    this._leaveTypeRepository = new GenericRepository<LeaveType>(_context);
                return _leaveTypeRepository;
            }
        }

        public GenericRepository<JobType> JobTypeRepository
        {
            get
            {
                if (this._JobTypeRepository == null)
                    this._JobTypeRepository = new GenericRepository<JobType>(_context);
                return _JobTypeRepository;
            }
        }

        public GenericRepository<HRMS_InterviewRound> InterviewRoundRepository
        {
            get
            {
                if (this._InterviewRoundRepository == null)
                    this._InterviewRoundRepository = new GenericRepository<HRMS_InterviewRound>(_context);
                return _InterviewRoundRepository;
            }
        }

        public GenericRepository<HRMS_InterviewVenueFloor> InterviewVenueFloorRepository
        {
            get
            {
                if (this._HRMS_InterviewVenueFloor == null)
                    this._HRMS_InterviewVenueFloor = new GenericRepository<HRMS_InterviewVenueFloor>(_context);
                return _HRMS_InterviewVenueFloor;
            }
        }

        public GenericRepository<HRMS_InterviewVenueRoom> InterviewVenueRoomRepository
        {
            get
            {
                if (this._HRMS_InterviewVenueRoom == null)
                    this._HRMS_InterviewVenueRoom = new GenericRepository<HRMS_InterviewVenueRoom>(_context);
                return _HRMS_InterviewVenueRoom;
            }
        }

        public GenericRepository<Relationship> RelationshipRepository
        {
            get
            {
                if (this._relationshipRepository == null)
                    this._relationshipRepository = new GenericRepository<Relationship>(_context);
                return _relationshipRepository;
            }
        }

        public GenericRepository<HRMS_JobTasks> HRMS_JobTasksRepository
        {
            get
            {
                if (this._HRMS_jobTasksRepository == null)
                    this._HRMS_jobTasksRepository = new GenericRepository<HRMS_JobTasks>(_context);
                return _HRMS_jobTasksRepository;
            }
        }
        public GenericRepository<HRMS_InterviewVenue> InterviewVenueRepository
        {
            get
            {
                if (this._hrms_InterviewVenuRepository == null)
                    this._hrms_InterviewVenuRepository = new GenericRepository<HRMS_InterviewVenue>(_context);
                return _hrms_InterviewVenuRepository;
            }
        }
        ///// <summary>
        ///// Get/Set Property for State repository.
        ///// </summary>
        //public GenericRepository<State> StateRepository
        //{
        //    get
        //    {
        //        if (this._stateRepository == null)
        //            this._stateRepository = new GenericRepository<State>(_context);
        //        return _stateRepository;
        //    }
        //}

        /// <summary>
        /// Get/Set Property for token repository.
        /// </summary>
        //public GenericRepository<Token> TokenRepository
        //{
        //    get
        //    {
        //        if (this._tokenRepository == null)
        //            this._tokenRepository = new GenericRepository<Token>(_context);
        //        return _tokenRepository;
        //    }
        //}
        #endregion

        #region Public member methods...
        /// <summary>
        /// Save method.
        /// </summary>
        public void Save()
        {
            try
            {
                _context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {

                var outputLines = new List<string>();
                foreach (var eve in e.EntityValidationErrors)
                {
                    outputLines.Add(string.Format("{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:", DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
                    foreach (var ve in eve.ValidationErrors)
                    {
                        outputLines.Add(string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage));
                    }
                }
                //System.IO.File.AppendAllLines(@"C:\errors.txt", outputLines);

                throw e;
            }

        }

        #endregion

        #region Implementing IDiosposable...

        #region private dispose variable declaration...
        private bool disposed = false;
        #endregion

        /// <summary>
        /// Protected Virtual Dispose method
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    Debug.WriteLine("UnitOfWork is being disposed");
                    _context.Dispose();
                }
            }
            this.disposed = true;
        }

        /// <summary>
        /// Dispose method
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion
    }
}

Generic Repository

#region Using Namespaces...

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;

#endregion

namespace DataModel.GenericRepository
{
    /// <summary>
    /// Generic Repository class for Entity Operations
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public class GenericRepository<TEntity> where TEntity : class
    {
        #region Private member variables...
        internal HrmsEntities Context;
        internal DbSet<TEntity> DbSet;
        #endregion

        #region Public Constructor...
        /// <summary>
        /// Public Constructor,initializes privately declared local variables.
        /// </summary>
        /// <param name="context"></param>
        public GenericRepository(HrmsEntities context)
        {
            this.Context = context;
            this.DbSet = context.Set<TEntity>();
        }
        #endregion

        #region Public member methods...

        /// <summary>
        /// generic Get method for Entities
        /// </summary>
        /// <returns></returns>
        public virtual IEnumerable<TEntity> Get()
        {
            IQueryable<TEntity> query = DbSet;
            return query.ToList();
        }

        /// <summary>
        /// Generic get method on the basis of id for Entities.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual TEntity GetByID(object id)
        {
            return DbSet.Find(id);
        }

        /// <summary>
        /// generic Insert method for the entities
        /// </summary>
        /// <param name="entity"></param>
        public virtual void Insert(TEntity entity)
        {
            DbSet.Add(entity);
        }

        /// <summary>
        /// Generic Delete method for the entities
        /// </summary>
        /// <param name="id"></param>
        public virtual void Delete(object id)
        {
            TEntity entityToDelete = DbSet.Find(id);
            Delete(entityToDelete);
        }

        /// <summary>
        /// Generic Delete method for the entities
        /// </summary>
        /// <param name="entityToDelete"></param>
        public virtual void Delete(TEntity entityToDelete)
        {
            if (Context.Entry(entityToDelete).State == EntityState.Detached)
            {
                DbSet.Attach(entityToDelete);
            }
            DbSet.Remove(entityToDelete);
        }

        /// <summary>
        /// Generic update method for the entities
        /// </summary>
        /// <param name="entityToUpdate"></param>
        public virtual void Update(TEntity entityToUpdate)
        {
            DbSet.Attach(entityToUpdate);
            Context.Entry(entityToUpdate).State = EntityState.Modified;
        }

        /// <summary>
        /// generic method to get many record on the basis of a condition.
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public virtual IEnumerable<TEntity> GetMany(Func<TEntity, bool> where)
        {
            return DbSet.Where(where).ToList();
        }

        /// <summary>
        /// generic method to get many record on the basis of a condition but query able.
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public virtual IQueryable<TEntity> GetManyQueryable(Func<TEntity, bool> where)
        {
            return DbSet.Where(where).AsQueryable();
        }

        /// <summary>
        /// generic get method , fetches data for the entities on the basis of condition.
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public TEntity Get(Func<TEntity, Boolean> where)
        {
            return DbSet.Where(where).FirstOrDefault<TEntity>();
        }

        /// <summary>
        /// generic delete method , deletes data for the entities on the basis of condition.
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public void Delete(Func<TEntity, Boolean> where)
        {
            IQueryable<TEntity> objects = DbSet.Where<TEntity>(where).AsQueryable();
            foreach (TEntity obj in objects)
                DbSet.Remove(obj);
        }

        /// <summary>
        /// generic method to fetch all the records from db
        /// </summary>
        /// <returns></returns>
        public virtual IEnumerable<TEntity> GetAll()
        {
            return DbSet.ToList();
        }

        /// <summary>
        /// Inclue multiple
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="include"></param>
        /// <returns></returns>
        public IQueryable<TEntity> GetWithInclude(System.Linq.Expressions.Expression<Func<TEntity, bool>> predicate, params string[] include)
        {
            IQueryable<TEntity> query = this.DbSet;
            query = include.Aggregate(query, (current, inc) => current.Include(inc));
            return query.Where(predicate);
        }

        /// <summary>
        /// Generic method to check if entity exists
        /// </summary>
        /// <param name="primaryKey"></param>
        /// <returns></returns>
        public bool Exists(object primaryKey)
        {
            return DbSet.Find(primaryKey) != null;
        }

        /// <summary>
        /// Gets a single record by the specified criteria (usually the unique identifier)
        /// </summary>
        /// <param name="predicate">Criteria to match on</param>
        /// <returns>A single record that matches the specified criteria</returns>
        public TEntity GetSingle(Func<TEntity, bool> predicate)
        {
            return DbSet.Single<TEntity>(predicate);
        }

        /// <summary>
        /// The first record matching the specified criteria
        /// </summary>
        /// <param name="predicate">Criteria to match on</param>
        /// <returns>A single record containing the first record matching the specified criteria</returns>
        public TEntity GetFirst(Func<TEntity, bool> predicate)
        {
            return DbSet.First<TEntity>(predicate);
        }


        #endregion
    }
}

Controller

using BusinessServices;
using BusinessEntities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace WebApiAzure.Controllers
{
    public class EducationCategoryController : ApiController
    {
        private readonly IEducationCategoryService _educationcategoryServices;

        #region Public Constructor

        public EducationCategoryController()
        {
            _educationcategoryServices = new EducationCategoryService();
        }

        #endregion

        // GET: api/EducationCategory
        public HttpResponseMessage Get()
        {
            var educationcategory = _educationcategoryServices.GetAllEducationCategory();
            if (educationcategory != null)
            {
                var educationcategoryEntities = educationcategory as List<EducationCategory> ?? educationcategory.ToList().Where(i => i.IsActive == true);
                if (educationcategoryEntities.Any())
                    return Request.CreateResponse(HttpStatusCode.OK, educationcategoryEntities);
            }

            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Education Category not found");
        }

        // GET: api/EducationCategory/5
        public HttpResponseMessage Get(int id)
        {
            var educationcategory = _educationcategoryServices.GetEducationCategoryById(id);
            if (educationcategory != null)
                return Request.CreateResponse<EducationCategory>(HttpStatusCode.OK, educationcategory);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No Education Category found for this id");
        }

        // POST: api/EducationCategory
        public int Post([FromBody]EducationCategory educationcategoryEntities)
        {
            return _educationcategoryServices.CreateEducationCategory(educationcategoryEntities);
        }

        // PUT: api/EducationCategory/5
        public bool Put(int id,[FromBody]EducationCategory educationcategoryEntities)
        {
            if (id > 0)
            {
                if (educationcategoryEntities.IsActive == true)
                {
                    return _educationcategoryServices.UpdateEducationCategory(id, educationcategoryEntities);
                }
                else
                {
                    return _educationcategoryServices.DeleteEducationCategory(id, educationcategoryEntities);
                }
            }
            return false;
        }

        // DELETE: api/EducationCategory/5
        public bool Delete(int id, [FromBody]EducationCategory educationcategoryEntities)
        {
            if (id > 0)
                return _educationcategoryServices.DeleteEducationCategory(id, educationcategoryEntities);
            return false;
        }
    }
}

Tuesday, 14 February 2017

Checkbox Edit

for(int i = 0; i < checkedListBox1.Items.Count; i++)
 {
  checkedListBox1.SetItemChecked(i, false);//First uncheck the old value!
  //
  for (int x = 0; x < values.Length; x++)
  {
           if (checkedListBox1.Items[i].ToString() == values[x])
           {
               //Check only if they match!
               checkedListBox1.SetItemChecked(i, true);
           }
  }
}

Thursday, 9 February 2017

Page Call

public partial class EducationCategoryMst : System.Web.UI.Page
    {
        List<EducationCategory> educationcategoryList = null;
        EducationCategory educationcategoryEntity = new EducationCategory();
        HttpClient client = new HttpClient();
        HttpResponseMessage hrm = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            var appsurl = ConfigurationManager.AppSettings["APIPath"].ToString();
            client.BaseAddress = new Uri(appsurl);
            if (!Page.IsPostBack)
            {
                //Add an Accept header for JSON format.
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                GetData();
            }
        }

        #region GetEducationCategory
        private void GetData()
        {
            try
            {
                HttpResponseMessage hrm = client.GetAsync("api/EducationCategory").Result;
                if (hrm.IsSuccessStatusCode)
                {
                    educationcategoryList = hrm.Content.ReadAsAsync<List<EducationCategory>>().Result;
                    eduCateGrid.DataSource = null;
                    eduCateGrid.DataSource = educationcategoryList;
                    eduCateGrid.DataBind();
                }
            }
            catch (Exception ex)
            {

            }
        }
        #endregion

        protected void Clear()
        {
            txtEduCateCode.Text = "";
            txtCategory.Text = "";
            txtDescription.Text = "";
        }

        #region SaveEducationCategory
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnSave.Text == "Save")
                {
                    //Add an Accept header for JSON format.
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    educationcategoryEntity.EducationCategory_Code = txtEduCateCode.Text;
                    educationcategoryEntity.EducationCategory_Name = txtCategory.Text;
                    educationcategoryEntity.EducationCategory_Description = txtDescription.Text;
                    educationcategoryEntity.InsertedBy = 1;
                    educationcategoryEntity.InsertedOn = DateTime.Now;
                    educationcategoryEntity.IsActive = true;
                    educationcategoryEntity.IsDelete = false;

                    HttpResponseMessage content = client.PostAsJsonAsync("api/EducationCategory", educationcategoryEntity).Result;
                    if (content.IsSuccessStatusCode)
                    {
                        //lblInfomation.Text = "City Added";
                        Clear();
                        GetData();
                    }
                    else
                    {
                        //lblInfomation.Text = "Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase;
                    }
                }
                else
                {
                    //Add an Accept header for JSON format.
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    string strID = eduCateGrid.MasterTableView.Items[0].GetDataKeyValue("EducationCategory_Id").ToString();
                    educationcategoryEntity.EducationCategory_Code = txtEduCateCode.Text;
                    educationcategoryEntity.EducationCategory_Name = txtCategory.Text;
                    educationcategoryEntity.EducationCategory_Description = txtDescription.Text;
                    educationcategoryEntity.LastModifiedBy = 1;
                    educationcategoryEntity.LastModifiedOn = DateTime.Now;
                    educationcategoryEntity.IsActive = true;
                    educationcategoryEntity.IsDelete = false;

                    HttpResponseMessage content = client.PutAsJsonAsync("api/EducationCategory/" + strID, educationcategoryEntity).Result;
                    if (content.IsSuccessStatusCode)
                    {
                        //lblInfomation.Text = "City Added";
                        Clear();
                        GetData();
                    }
                    else
                    {
                        //lblInfomation.Text = "Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase;
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }
        #endregion
    }


Web Config

<appSettings>
<add key="APIPath" value="http://localhost:49370/"/>
  </appSettings>

Tuesday, 7 February 2017

  Select One Checkbox

 <script type="text/javascript">
        function CheckBoxCheck(rb) {
            var gv = document.getElementById("<%=datagrid.ClientID%>");
            var chk = gv.getElementsByTagName("input");
            var row = rb.parentNode.parentNode;
            for (var i = 0; i < chk.length; i++) {
                if (chk[i].type == "checkbox") {
                    if (chk[i].checked && chk[i] != rb) {
                        chk[i].checked = false;
                        break;
                    }
                }
            }
        }
    </script>

 <asp:TemplateField HeaderStyle-Width="20px" ItemStyle-HorizontalAlign="Center">
                            <ItemTemplate>
                                <asp:CheckBox runat="server" ID="chkRow"  OnCheckedChanged="chkRow_CheckedChanged" AutoPostBack="true"  onclick="CheckBoxCheck(this)" />
                            </ItemTemplate>
                         </asp:TemplateField>

foreach (GridViewRow row in datagrid.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    CheckBox chkRow = (row.Cells[1].FindControl("chkRow") as CheckBox);
                    if (chkRow.Checked == true)
                    {
                        lblprofileid.Text = row.Cells[2].Text;
                        int Id = Convert.ToInt32(row.Cells[2].Text);
                        var View = (from P in pe.TblProfiles where P.ProfileId == Id select P).ToList();
                        imgPhoto.ImageUrl = View.ToList()[0].Image;

                        string[] Profile_Name = row.Cells[3].Text.Split(' ');
                        txtFirstName.Text = Profile_Name[0];
                        txtMiddleName.Text = Profile_Name[1];
                        txtLastName.Text = Profile_Name[2];
                        ddlCountry.SelectedValue = row.Cells[4].Text.ToString();
                        ddlState.SelectedValue = row.Cells[5].Text.ToString();
                        ddlCity.SelectedValue = row.Cells[6].Text.ToString();
                        txtAddress.Text = row.Cells[7].Text;
                        txtEmail.Text = row.Cells[8].Text;

                        string[] MobNo = row.Cells[9].Text.Split('-');
                        txtMobCode.Text = MobNo[0];
                        txtMobNo.Text = MobNo[1];

                        //if (MobNo = row.Cells[9].Text.ToString())
                        //{
                        //    txtMobCode.Text = MobNo[0];
                        //    txtMobNo.Text = MobNo[1];
                        //}
                        //else
                        //{
                        //    txtMobNo.Text = row.Cells[9].Text;
                        //}

                        btnSubmit.Text = "Update";
                    }
                }
            }

Monday, 6 February 2017

 SCRIPT VALIDATION

<script language="javascript" type="text/javascript">
        function chkfrm()
        {
            if(!/\S/.test(document.getElementById("txtApplicantUserName").value))
            {
                alert("Please Enter User Name !!");
                document.getElementById("txtApplicantUserName").focus();
                return false;
            }
            if(!/\S/.test(document.getElementById("txtApplicantPassword").value))
            {
                alert("Please Enter Password !!");
                document.getElementById("txtApplicantPassword").focus();
                return false;
            }
            if(!/\S/.test(document.getElementById("txtApplicantCaptcha").value))
            {
                alert("Please Enter Captcha !!");
                document.getElementById("txtApplicantCaptcha").focus();
                return false;
            }
            return true;
        }
        function chkfrmAdmin()
        {
            if(document.getElementById("ddl_logintype").value=="%")
            {
                alert("Please Select Login Type !!");
                document.getElementById("ddl_logintype").focus();
                return false;
            }
            if(!/\S/.test(document.getElementById("txtUserName").value))
            {
                alert("Please Enter User Name !!");
                document.getElementById("txtUserName").focus();
                return false;
            }
            if(!/\S/.test(document.getElementById("txtpsw").value))
            {
                alert("Please Enter Password !!");
                document.getElementById("txtpsw").focus();
                return false;
            }
            if(!/\S/.test(document.getElementById("txtCaptcha").value))
            {
                alert("Please Enter Captcha !!");
                document.getElementById("txtCaptcha").focus();
                return false;
            }
            return true;
        }
       
          function onfocusset(it)
        {
            document.getElementById(it).className="inputonfocus";
        }
        function onblurset(it)
        {
            document.getElementById(it).className="inputonblur";
        }
    </script>

///////////////////////================================\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

onclick="return chkfrm();WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("btnApplicantLogin", "", true, "", "", false, false))"