Uncategorized

ASP.NET Identity reset password


var Db = new ApplicationDbContext();
var userDetail = Db.Users.FirstOrDefault(u => u.UserName.Equals(Username));

String userId = userDetail.Id;
String newPassword = "pa$$word";
ApplicationUser cUser = UserManager.FindById(userId);
String hashedNewPassword = UserManager.PasswordHasher.HashPassword(newPassword);
UserStore store = new UserStore();
cUser.PasswordHash = hashedNewPassword;
UserManager.UpdateAsync(cUser);
Db.SaveChanges();

UnitOfWork Generic Repository

The repository and unit of work patterns are intended to create an abstraction layer between the data access layer and the business logic layer of an application. Implementing these patterns can help insulate your application from changes in the data store and can facilitate automated unit testing or test-driven development (TDD).

UnitOfwork


  public class UnitOfWork : IUnitOfWork
    {
        public DataBaseEntities _context;

        #region Constructor
        public UnitOfWork()
        {
            _context = new DataBaseEntities ();
        }
        #endregion

        #region Implement Inteface Methods

        public void Commit()
        {
            _context.SaveChanges();
        }

        public void CommitAndRefreshChanges()
        {
            bool saveFailed = false;

            do
            {
                try
                {
                    _context.SaveChanges();
                    saveFailed = false;
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    saveFailed = true;

                    ex.Entries.ToList()
                              .ForEach(entry =>
                              {
                                  entry.OriginalValues.SetValues(entry.GetDatabaseValues());
                              });

                }
            } while (saveFailed);
        }

        public void RollbackChanges()
        {
            // set all entities in change tracker 
            // as 'unchanged state'
            _context.ChangeTracker.Entries()
                              .ToList()
                              .ForEach(entry => entry.State = System.Data.Entity.EntityState.Unchanged);
        }

        public IEnumerable ExecuteQuery(string sqlQuery, params object[] parameters)
        {
            return _context.Database.SqlQuery(sqlQuery, parameters);
        }

        public int ExecuteCommand(string sqlCommand, params object[] parameters)
        {
            return _context.Database.ExecuteSqlCommand(sqlCommand, parameters);
        }

        private bool _disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this._disposed)
            {
                if (disposing)
                {
                    _context.Dispose();
                }
            }
            this._disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion

  public List ExecuteQueryForDropdown(string sqlQuery)
        {
            var result = db.Database.SqlQuery(sqlQuery).ToList();
            return result;
        }

 public IQueryable Filter(Expression<Func> filter, string orderByColumnName, bool ascending, out int total, int index = 0, int size = 50)
        {
            int skipCount = index * size;
            var resetSet = filter != null ? table.Where(filter).AsQueryable() : table.AsQueryable();
           
            total = resetSet.Count();


            if (!string.IsNullOrEmpty(orderByColumnName))
            {
                resetSet = resetSet.OrderBy(orderByColumnName, ascending);
                resetSet = skipCount == 0 ? resetSet.Take(size) : resetSet.Skip(skipCount).Take(size);
            }
            return resetSet.AsQueryable();
        }

        #region Repositories

        #endregion
    }

Interface of UnitOfWork


 public interface IUnitOfWork : IDisposable
    {
        /// 
        /// Commit all changes made in a container.
        /// 
        void Commit();

        /// 
        ///  If the entity have fixed properties and any optimistic concurrency problem exists,
        ///  then 'client changes' are refreshed - Client wins
        /// 
        void CommitAndRefreshChanges();

        /// 
        /// Rollback tracked changes. See references of UnitOfWork pattern
        /// 
        void RollbackChanges();

        /// 
        /// Execute specific query with underliying persistence store
        /// 
        /// Entity type to map query results
        /// 
        /// SELECT idCustomer,Name FROM dbo.[Customers] WHERE idCustomer > {0}
        /// 
        /// 
        /// 
        /// 
        IEnumerable ExecuteQuery(string sqlQuery, params object[] parameters);

        /// 
        /// Execute arbitrary command into underliying persistence store
        /// 
        /// 
        /// Command to execute
        /// 
        /// SELECT idCustomer,Name FROM dbo.[Customers] WHERE idCustomer > {0}
        /// 
        ///
        /// A vector of parameters values
        /// The number of affected records
        int ExecuteCommand(string sqlCommand, params object[] parameters);

 List ExecuteQueryForDropdown(string sqlQuery);

        IQueryable Filter(Expression<Func> filter, string orderByColumnName, bool ascending, out int total, int index = 0, int size = 20);
    }

Generic Repository


 public class RepositoryBase where T : class
    {
        internal TSPEntities _dataContext;
        internal DbSet _dbset;

        public RepositoryBase(TSPEntities context)
        {
            this._dataContext = context;
            this._dbset = context.Set();
        }

        /// 
        /// Paging Query with filter
        /// 
        /// 
        /// 
        /// 
        /// 
        public virtual List Get(Expression<Func> filter = null, Func<IQueryable, IOrderedQueryable> orderBy = null, string includeProperties = "")
        {
            IQueryable query = _dbset;

            if (filter != null)
            {
                query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty);
            }

            if (orderBy != null)
            {
                return orderBy(query).ToList();
            }
            else
            {
                return query.ToList();
            }
        }

        /// 
        /// Get selected records with paging
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public virtual IEnumerable GetPaged(int pageIndex, int pageCount, System.Linq.Expressions.Expression<Func> orderByExpression, bool ascending)
        {
            var set = _dbset;

            if (ascending)
            {
                return set.OrderBy(orderByExpression)
                          .Skip(pageCount * pageIndex)
                          .Take(pageCount);
            }
            else
            {
                return set.OrderByDescending(orderByExpression)
                          .Skip(pageCount * pageIndex)
                          .Take(pageCount);
            }
        }

        public virtual void Add(T entity)
        {
            _dbset.Add(entity);
        }

        public virtual void Delete(T entity)
        {
            _dbset.Remove(entity);
        }

        public virtual void Delete(Expression<Func> where)
        {
            IEnumerable objects = _dbset.Where(where).AsEnumerable();
            foreach (T obj in objects)
                _dbset.Remove(obj);
        }

        public virtual T GetById(long id)
        {
            return _dbset.Find(id);
        }

        public virtual T GetById(string id)
        {
            return _dbset.Find(id);
        }

        public virtual IEnumerable GetAll()
        {
            return _dbset.ToList();
        }

        public virtual IQueryable GetAllQueryable()
        {
            return _dbset.AsQueryable();
        }

        public virtual IEnumerable GetMany(Expression<Func> where)
        {
            return _dbset.Where(where).ToList();
        }

        public virtual IQueryable GetManyQueryable(Expression<Func> where)
        {
            return _dbset.AsQueryable().Where(where);
        }

        public T Get(Expression<Func> where)
        {
            return _dbset.Where(where).FirstOrDefault();
        }

 public IQueryable Filter(Expression<Func> filter, string orderByColumnName, bool ascending, out int total, int index = 0, int size = 50)
        {
            int skipCount = index * size;
            var resetSet = filter != null ? table.Where(filter).AsQueryable() : table.AsQueryable();
           
            total = resetSet.Count();


            if (!string.IsNullOrEmpty(orderByColumnName))
            {
                resetSet = resetSet.OrderBy(orderByColumnName, ascending);
                resetSet = skipCount == 0 ? resetSet.Take(size) : resetSet.Skip(skipCount).Take(size);
            }
            return resetSet.AsQueryable();
        }
    }

Export DataTable to Excel/CSV C#


protected void btnExport_Click(object sender, EventArgs e)
    {
        DataTable dtTable = new DataTable();
        DataRow dtRow;

        dtTable.Columns.Add("SNo", typeof(int));
        dtTable.Columns.Add("Address", typeof(string));

        for (int i = 0; i <= 9; i++)
        {
            dtRow = dtTable.NewRow();
            dtRow[0] = i;
            dtRow[1] = "Address " + i.ToString();
            dtTable.Rows.Add(dtRow);
        }

        Response.ContentType = "Application/x-msexcel";
        Response.AddHeader("content-disposition", "attachment;filename=test.csv");
        Response.Write(ExportToCSVFile(dtTable));
        Response.End();
    }

    private string ExportToCSVFile(DataTable dtTable)
    {
        StringBuilder sbldr = new StringBuilder();
        if (dtTable.Columns.Count != 0)
        {
            foreach (DataColumn col in dtTable.Columns)
            {
                sbldr.Append(col.ColumnName + ',');
            }
            sbldr.Append("\r\n");
            foreach (DataRow row in dtTable.Rows)
            {
                foreach (DataColumn column in dtTable.Columns)
                {
                    sbldr.Append(row[column].ToString() + ',');
                }
                sbldr.Append("\r\n");
            }
        }
        return sbldr.ToString();
    }
}

Attendance UNPIVOT first then Pivot for count present, absent etc in SQL

Sample data download: here

Declare @tempAttendance table(EmpID int, EmpName varchar(50), edate int, ecode varchar(5))

	insert into @tempAttendance 
	SELECT empid, empname, code as 'edate', value as 'ecode'
	FROM [dbo].[hattendance]
	UNPIVOT (
		value FOR code IN (
			 [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30], [31]
		)
	) unpiv

	--select * from  @tempAttendance

	SELECT empid, empname, P , A, FH, NA
	FROM
	(SELECT empid, empname, ecode
	FROM @tempAttendance )  ps
	PIVOT
	(
	count (ecode)
	FOR Ecode IN
	( P , A, FH, NA )
	) AS pvt order by empid

download sql file from here

Dynamically create columns in a temp table and generate pivot report

Sample Data download: http://goo.gl/lcOf8z

Sample survey submitted data

Generate excel report as below.

Username, Address, City, State, Zip, Question 1, Question 2, Question 3, …..
Prakash, test, anand, gujarat, 388001, Answer 1, Answer 2, Answer 3,..
Chirag, test, anand, gujarat, 388001, Answer 1, Answer 2, Answer 3,..


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Prakash Rathod
-- Create date: 18-Mar-2014
-- Description:	Generate dynamic pivot report of submited survey
-- Exec spSubmitedSurveyExcelReport 'FCDC5B31-58D6-4C25-92ED-74665E343141'
-- =============================================
ALTER PROCEDURE spSubmitedSurveyExcelReport
	@SurveyID uniqueidentifier
AS
BEGIN	
	SET NOCOUNT ON;
	
	create table #distictCaption (caption nvarchar(1000)) -- create temporary table for storing questions.

	insert into #distictCaption
	Select distinct caption From submitedsurvey s join users u on u.id = s.userid where surveyid=@SurveyID

	Create table #tempSurveyAnswer (userid uniqueidentifier, Name varchar(200), [Address] varchar(500), city varchar(200) , [state] varchar(200), zip varchar(10), dummy bit) -- create temp table for creating dynamic columns, questions become columns

	Declare @Script as Varchar(8000);
	Declare @Script_prepare as Varchar(8000);
	 
	Set @Script_prepare = 'Alter table #tempSurveyAnswer Add [?] varchar(100);'
	Set @Script = ''

	Select
				@Script = @Script + Replace(@Script_prepare, '?', caption)
	From #distictCaption 

	Exec (@Script)
	 
	Alter table #tempSurveyAnswer drop column dummy;

	insert into #tempSurveyAnswer(userid ,Name, [Address], City, [State], Zip) 
	select s.userid, u.firstname, u.[Address], u.City, u.[State], u.Zip from submitedsurvey s
	join users u on u.id = s.userid
	where surveyid=@SurveyID group by s.userid, u.firstname, u.[Address], u.City, u.[State], u.Zip
	 
-- update temp table
	DECLARE @sql NVARCHAR(MAX)
	SET @sql = ''

	select @sql = @sql + ' UPDATE #tempSurveyAnswer ' + CHAR(13) +
	' SET [' + c.name + '] = (SELECT value ' + CHAR(13) +
	' FROM submitedsurvey' + CHAR(13) +
	' where surveyid=@I and #tempSurveyAnswer.userid = submitedsurvey.userid and submitedsurvey.caption = ''' + c.name + ''') '+ CHAR(13) 
	from tempdb.sys.columns c
	where object_id = object_id('tempdb..#tempSurveyAnswer') and name'userid' and name'Name' and name  'Address' and name'city' and name'state' and
	name'zip';

	print(@sql)

	exec sp_executesql @sql,N'@I uniqueidentifier',@I=@SurveyID;

	Select * from #tempSurveyAnswer;

	drop table #distictCaption
	drop table #tempSurveyAnswer
END
GO


Add Comma into number using javascript


<script>

addCommas = function(input){
  // If the regex doesn't match, `replace` returns the string unmodified
  return (input.toString()).replace(
    // Each parentheses group (or 'capture') in this regex becomes an argument 
    // to the function; in this case, every argument after 'match'
    /^([-+]?)(0?)(\d+)(.?)(\d+)$/g, function(match, sign, zeros, before, decimal, after) {

      // Less obtrusive than adding 'reverse' method on all strings
      var reverseString = function(string) { return string.split('').reverse().join(''); };

      // Insert commas every three characters from the right
      var insertCommas  = function(string) { 

        // Reverse, because it's easier to do things from the left
        var reversed           = reverseString(string);

        // Add commas every three characters
        var reversedWithCommas = reversed.match(/.{1,3}/g).join(',');

        // Reverse again (back to normal)
        return reverseString(reversedWithCommas);
      };

      // If there was no decimal, the last capture grabs the final digit, so
      // we have to put it back together with the 'before' substring
      return sign + (decimal ? insertCommas(before) + decimal + after : insertCommas(before + after));
    }
  );
};

</script>

How to call this function?

$.fn.addCommas = function() {
$(this).each(function(){
$(this).text(addCommas($(this).text()));
});
};

calling [Ajax.AjaxMethod()] not working

finally its resolved by using,

<system.webServer>
<validation validateIntegratedModeConfiguration=”false” />
<modules>
<add name=”ScriptModule” preCondition=”integratedMode” type=”System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ />
</modules>
<handlers>
<remove name=”WebServiceHandlerFactory-Integrated” />

<add verb=”POST,GET” name=”Ajax” path=”ajax/*.ashx” type=”Ajax.PageHandlerFactory, Ajax” />
<add name=”ScriptHandlerFactory” verb=”*” path=”*.asmx” preCondition=”integratedMode” type=”System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ />
<add name=”ScriptHandlerFactoryAppServices” verb=”*” path=”*_AppService.axd” preCondition=”integratedMode” type=”System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ />
<add name=”ScriptResource” preCondition=”integratedMode” verb=”GET,HEAD” path=”ScriptResource.axd” type=”System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ />
</handlers>
</system.webServer>

<system.web>
<httpHandlers>
<add verb=”POST,GET” path=”ajax/*.ashx” type=”Ajax.PageHandlerFactory, Ajax”/>
</httpHandlers>
</system.web>

Android SDK Manager does not open in windows 8

I have installed windows 8 in my laptop and tried to open ‘Android SDK Manager’. It was not open. By googling I found the solution as below.

Go to android-sdk folder what you had set path under windows->preference menu for android.
Edit android.bat file.
Find java_exe=
And in front of add Java.exe path like “C:\Program Files (x86)\Java\jdk1.6.0\bin\java.exe”

how to read resource file in jquery or javascript or js file

As generally we do in asp.net project, I have created a global resource file for storing common error messages, info messages, labels etc in my first MVC4 project. I used ready-made validation.js for giving validation. I have face the problem how to get the resource file’s object value in .js file. From come out this problem I have find a way. I had create a controller ‘ResoruceScript’. And added below code in ActionResult method.

        public ActionResult Index()
        {
            Response.Clear();            
            Response.ContentType = "text/javascript";
            
            return View();
        }

Then create a view for “Index” Action. And remove the html content, all tags which are added by default when we create a new view. And below code.


        @using System.Collections
@using System.Globalization
@using System.Resources
@using Pharma
@{
    Layout = null;
    // Get a set of resources appropriate to the culture defined by the browser
    ResourceSet resourceSet = @Resources.PharmaCore.ResourceManager.GetResourceSet
        (CultureInfo.CurrentUICulture, true, true);
}

// Define the empty object in javascript
var Resources = {};
@foreach (DictionaryEntry res in resourceSet)
{
    // Create a property on the javascript object for each text resource
    @:Resources.@res.Key = "@Html.Raw(
        HttpUtility.JavaScriptStringEncode(res.Value.ToString()))";
}

Here, PharmaCore is my resource file name. Above code create the array of resource file’s objects. Add this view as javascript file in head tag or anywhere in the page but before the use of resource value. I have added in head tag of page.

 <script src="~/ResourceScript"&gtl</script>

Now, you are able to get the resource file’s object value as ‘Resources.rfv_Common_Msg’ in .js file.