Wednesday, 3 May 2017

Configure TypeScript in VS 2013

While use typescript in VS 2013 everyone want to find the solution for
"typescript json configuration file not found in VS2013"

To execute the typescript and produce the respect JS please add the below code in your project file  instead of  typescriptjsonconfiguration file because this file only available in VS 2015.

/*Start*/

 <PropertyGroup Condition="'$(Configuration)' == 'Debug'">
    <TypeScriptTarget>ES5</TypeScriptTarget>
    <TypeScriptModuleKind>commonjs</TypeScriptModuleKind>
    <TypeScriptModuleResolution>node</TypeScriptModuleResolution>
    <TypeScriptSourceMap>True</TypeScriptSourceMap>
    <TypeScriptEmitDecoratorMetadata>True</TypeScriptEmitDecoratorMetadata>
    <TypeScriptExperimentalDecorators>True</TypeScriptExperimentalDecorators>
    <TypeScriptRemoveComments>False</TypeScriptRemoveComments>
    <TypeScriptNoImplicitAny>True</TypeScriptNoImplicitAny>
  </PropertyGroup>

/*End*/


How to add this in project file:
1. goto the folder location of your project(open project in file explorer)
2.there you can see the Visual C# project file just write click and edit that in notepad
3.There you can see the different <propertyGroup> tags below of one tag add the above code.
  then run the application .

Thanks
Pradeep

Monday, 30 May 2016

Maintain Session For Login User Using ActionFilter in Asp.Net MVC

Action Filter
Action filters contain logic that is executed before and after a controller action executes.
2methods we can override from the action filter.

1. OnActionExecuting :before execution
2. OnActionExecuted  :After execution

Check session value on Action Filter
1. Create a class (e.g  SessionExpire ) derived from ActionFilterAttribute Class.

public class SessionExpire:ActionFilterAttribute


2. Override the OnActionExecuting method in created class (SessionExpire) .
       public override void OnActionExecuting(ActionExecutingContext filterContext)
{
……….
……….
}

3. In side this method check the session value is available or not, if not available then redirect to login page.


public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if ((HttpContext.Current.Session["UserName"] == null) ||                                                                                
                                 (HttpContext.Current.Session["UserID"]==null))
               {
         filterContext.Result = new RedirectResult("~/Account/Login");
         return;
                      }
4. How to use in Action Method of controller:
We can use this by the class name derived from ActionFilterAttribute in the controller.
 [SessionExpire]
        public ActionResult SubmitTimesheet()
        {
………………..
………………….
 }
These are the simple steps to check session in Action level

Restrict different Users for specific Action Method of  controller
1. If we are Using Roll in Db to restrict different user for different controllers
We have to modify little bit code on that . i.e if a user of contractor want to access a method of admin then it should show you are not authorized for that page

Suppose we have 3 users namely below
User Roll Id User Roll Name
1 Contractor
2 Approver
3 Admin

2. While login we are storing the user type in session as below
      HttpContext.Current.Session["UserType"]=user.userid;
3. To check the action method belongs to particular user type or not we have to pass the user type from action method to SessionExpire  class derived from ActionFilterAttribute Class.
Like:
[SessionExpire(<UserType>)]

[SessionExpire(1)]
        public ActionResult SubmitTimesheet()
        {
………………..
………………….\
Return view();
               }
4. To get the User Type and validate with session value of user Type we have to modify the SessionExpire Class.
    public class SessionExpire:ActionFilterAttribute
    {
 public int sessionid { get; set; }
        public SessionExpire(int roll=999)
        {
            sessionid = roll;
        }
       public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
……….
……….
 }
     }
Note: By default roll is 999 if we are not passing any value from action method if we are passing “1” then roll will be “1” and that will assign to “sessionid” property


5. Below are the code used to check the session value with passed usertype from action method
in OnActionExecuting Method .

public class SessionExpire:ActionFilterAttribute
    {
        public int sessionid { get; set; }

        public SessionExpire(int roll=999)
        {
            sessionid = roll;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
       if ((HttpContext.Current.Session["UserName"] == null) ||
         (HttpContext.Current.Session["UserID"]==null))  (Note:Checking for session exist or not )
                {
                    filterContext.Result = new RedirectResult("~/Account/Login");
                    return;
                }


  if ((int)HttpContext.Current.Session["UserType"] != sessionid)
           (Note: Checking stored session id match to passed usertype id from action )
       {
             if ((int)HttpContext.Current.Session["UserType"] == 1)
      (Note: check with login Usertype and redirect to Unauthorized page of Login User )
                {
                filterContext.Result =
                new RedirectResult("~/Contractor/notauthorised");
                    return;
                }

            if ((int)HttpContext.Current.Session["UserType"] == 2)
                {
                 filterContext.Result = new RedirectResult("~/Approver/notauthorised");
                 return;
                }
            if ((int)HttpContext.Current.Session["UserType"] == 3)
                {
             filterContext.Result = new RedirectResult("~/Admin/notauthorised");
              return;
                }
         }
                base.OnActionExecuting(filterContext);
   }
}






Redirect to Particular page when Session Fails in Action Filter

When we are working in particular page and that time session fails then it will Navigate to login page and after login page it should redirect to That page instead of home page . I did this with Action filter.

1. If session fails Store the Url in a session
2. After signin redirect to session stored Url
As Code
public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
        if ((HttpContext.Current.Session["UserName"] == null) ||                                            
(HttpContext.Current.Session["UserID"]==null))
(Note: Checking for session fails or not  ? if fails then store in a new session variable for redirect after login )
        {              
HttpContext.Current.Session["Urlreturn"] = HttpContext.Current.Request.Url+"";
filterContext.Result = new RedirectResult("~/Account/Login");
return;

        }
 }


In Login action check if data exist in session then rediredct to that page

if ((Session["Urlreturn"] as string) != null)
(Note :checking for stored Url is Exist after login)
                {
                    return Redirect((Session["Urlreturn"] + ""));
(Note: If exist then redirect to Stored URL where session fails)
                }


Thanks,


Pradeep Kumar Das

Wednesday, 12 August 2015

How to Use a edmx file for multiple DB having same type of table and schema.

1.There are 3 database are have same type of table for 3 application.


Tables are

2.Another database to manage the applications  having a table to store the Application ID ,server name,DBname,Password and username  of application database.






3. create a Edmx file for a Application that will work as a template and another
 for the DB to manage Application



                                                           (for manage applications)
4.while creating the edmx file the class  generate by edmx file is

5. Create a class of same class name as above with a parameterized constructor to pass the connection string to this for change the Db connection string dynamically .


6. based on the application id we will get the database detail and pass to the function to change the connection string .

 Copy the connection  string for applicationDB from web.config file and put that in a string and change the server name, DBname, Password and username  of application based on Appid.

7.GetuserDBbyAppid() function we will get the entity for the particular DB .then we can use the Entity Framework to curd operation on that DB.
Like

USE of this:
 Need not required to create edmx file for same type of database which are situated in different servers and all server can manage through a application means we can create users in base application so that user can login in assigned application .



thanks ,
Pradeep Kumar Das 

Tuesday, 20 January 2015

When we sending mail if you trouble shooting with this Error

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at + working on one gmail account.

To solve this Error just go to this links

https://accounts.google.com/DisplayUnlockCaptcha
https://www.google.com/settings/security/lesssecureapps

Code for Sending Email:

System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
        mail.To.Add("Toaddress");
        mail.From = new MailAddress("from mail", "Email head", System.Text.Encoding.UTF8);
        mail.Subject = "This mail is send from asp.net application";
        mail.SubjectEncoding = System.Text.Encoding.UTF8;
        mail.Body = "This is Email Body Text";
        mail.BodyEncoding = System.Text.Encoding.UTF8;
        mail.IsBodyHtml = true;
        mail.Priority = MailPriority.High;

        SmtpClient client = new SmtpClient();
       // client.EnableSsl = true;
        client.UseDefaultCredentials = false;

        client.Credentials = new System.Net.NetworkCredential("from mail", "from mail Password");
        client.Port = 587;
        client.Host = "smtp.gmail.com";
        client.EnableSsl = true;
       
        try
        {
            client.Send(mail);
        }
        catch (Exception ex)
        {
            throw;

        }

Reference Link:
http://forums.asp.net/t/2021213.aspx?sending+email+via+gmail+not+working+authentication+problem

If you have any Queries please contact lakshmibindu.cse@gmail.com

Friday, 17 October 2014

How to use multiple aggregate functions in a single query(without sub query) in oracle/sql server


Here i am using two count functions with different conditions in a single query.


select count(case when department_id = 10 and salary<5000 then 1 end), 
          count(case when department_id = 20 then 1 end) 
from employees;

Output:





If we want the output as the two results in same column,


select count(EMPLOYEE_ID) from employees where DEPARTMENT_ID=30 and salary<5000
union all

select count(EMPLOYEE_ID) from EMPLOYEES where DEPARTMENT_ID=50;

Output:








References: http://stackoverflow.com/questions/12789396/how-to-get-multiple-counts-with-one-sql-query.


Five things to remember to improve the stored procedure performance while create stored procedure in SQL Server

Steps to improve the performance  of Stored procedure in SQL Server

 1) Set NOCOUNT ON;
 2) Don't use input parameters directly. Assign them to Locally  declared variables in stored procedure.
 3) Don't use Count(*) use Count(pk_Id)
 4) Use Exists instead of IN in where condition
 5) Use distinct instead of Group by clause in all possible cases

Example stored procedure
 Here my using group by clause to full file my requirement. Try to avoid the using of group by clause

ALTER PROCEDURE [dbo].[your sp name here] 
@warehouseId char(4)
AS
BEGIN
    SET NOCOUNT ON;
    Declare @Local_warehouseId char(4)=@warehouseId
   
    select oh.OrderNum,case when od.picked is null then 0 else od.picked end as picked,oh.numLines,mem.firstName,mem.lastName,mem.phone,mem.Suburb,oh.memberid as memberID,oh.PickUpPointTimeSlot as EstPickUpTime  from OrderHeader oh join 
members mem on mem.memberID=oh.memberid
join PickupPointTimes pPoint on pPoint.PickupPointID=oh.PickupPointID and oh.PickUpPointTimeSlot=pPoint.TimeSlot and pPoint.PickUpDay=oh.pickupDay
Left outer join (select OrderNum,COUNT(LineItemID) as picked from OrderDetails where PickedQTY is not null group by OrderNum )  as od  on od.OrderNum=oh.OrderNum 
where exists (select * from PickupPoints pp where pp.PickupPointID=oh.PickupPointID and WarehouseID=@Local_warehouseId) and oh.status='RP'
order by pPoint.SortCode,oh.numLines
 
END

Thursday, 9 October 2014

Label and Barcode printing using ZPL printer from C#.Net


Printing label and Barcodes using ZPL printer from C#.Net

  Here I am printing Label using PrintLabel Method and printing Barcode  using PrintBarcode method. We can use this code windows,web or any other applications which are using code behide as C#.Net. It's works if ZPL printer is connected via parallel port or via Bluetooth to your system.

Here I am passing ZPL language command  to zpl printer (zpl printer supports EPL and ZPL commands).

Note:Code is written according to my requirements. You can change it according to your requirements. If anyone needs help then you can shoot an email to hareesh434@gmail.com with subject as Share your doubts and answers with IT world. If I can i will help you.

C#.Net  Code

Below class  is for passing the ZPL command to printer

  public class UpcLabel
    {

        private string strFirstName;
        private string strLastName;
        private string strNoOfCopies;
        private string PickUpTime;
        private string Cold;
        private string NewMember;
        public UpcLabel()
        {
        }
        public UpcLabel(string strFirstName, string strLastName, string strNoOfCopies, string PickUpTime, string Cold, string NewMember)
        {
            if (strFirstName == null || strLastName == null || strNoOfCopies == "" || strNoOfCopies=="0")
            {
                throw new ArgumentNullException("strFirstName");
            }

            this.strFirstName = strFirstName;
            this.strLastName = strLastName;
            this.strNoOfCopies = strNoOfCopies;
            this.PickUpTime = PickUpTime;
            this.Cold = Cold;
            this.NewMember = NewMember;
        }
        public void PrintBarcode(string printerName, string pProductName, string pBarcode,string strNumOfCopies)
        {
            if (printerName == null)
            {
                throw new ArgumentNullException("printerName");
            }
            StringBuilder strBldr = new StringBuilder();
            strBldr.AppendLine("^XA");

            strBldr.AppendLine("^FO40,100");
            strBldr.AppendLine("^AQ,50,30");
            // sb1.AppendLine("^FDAnja^FS");
            strBldr.AppendLine(string.Format(CultureInfo.InvariantCulture, "^FD{0}^FS", pProductName));
            //^FO100,100^BY3
            strBldr.AppendLine("^FO80,200^BY3");
            //^BCN,150,Y,N,Y,N
            strBldr.AppendLine("^BCN,125,Y,N,Y,N");
            strBldr.AppendLine(string.Format(CultureInfo.InvariantCulture, "^FD{0}^FS", pBarcode));
            strBldr.AppendLine(string.Format(CultureInfo.InvariantCulture, "^PQ{0}", strNumOfCopies));
            strBldr.AppendLine("^XZ");
            RawPrinterHelper.SendStringToPrinter(printerName, strBldr.ToString());



        }
        public void Print(string printerName)
        {
            if (printerName == null)
            {
                throw new ArgumentNullException("printerName");
            }
            StringBuilder sb1=new StringBuilder();
            //^XA=Indicates Starting of Zpl
                sb1.AppendLine("^XA");
                sb1.AppendLine("^LL350");//^FS
                sb1.AppendLine("^PW930");//^FS
                sb1.AppendLine("^FO10,10");
                sb1.AppendLine("^AQ,80,80");
                // sb1.AppendLine("^FDAnja^FS");

                //FOa,b
                //a=Postion from x-axis
                //b=Position from y-axis
                //Aa,b,c
                //a=Font size Like Q,V,R,0
                //b=Font width
                //c=Font Height
             
                sb1.AppendLine(string.Format(CultureInfo.InvariantCulture, "^FD{0}^FS", this.strFirstName));
                sb1.AppendLine("^FO10,68");
                sb1.AppendLine("^AQ,80,80");
                sb1.AppendLine(string.Format(CultureInfo.InvariantCulture, "^FD{0}^FS", this.strLastName));
       
            sb1.AppendLine("^FO10,150");
            sb1.AppendLine("^AQ,50,50");
            sb1.AppendLine(string.Format(CultureInfo.InvariantCulture, "^FD{0}^FS", this.PickUpTime));

            sb1.AppendLine("^FO240,150");
            sb1.AppendLine("^AQ,50,50");
            sb1.AppendLine(string.Format(CultureInfo.InvariantCulture,"^FD{0}^FS",this.Cold));
            //^PQ2= Indicates number of copies to print
            sb1.AppendLine(string.Format(CultureInfo.InvariantCulture, "^PQ{0}", this.strNoOfCopies));
            //sb1.AppendLine("^PQ2");
            //^XZ=Indicates ending of ZPL page
            sb1.AppendLine("^XZ");
            RawPrinterHelper.SendStringToPrinter(printerName, sb1.ToString());
            //for (int counter = 0; counter <Convert.ToInt32(this.strNoOfCopies); counter++)
            //{
            //    RawPrinterHelper.SendStringToPrinter(printerName, sb1.ToString());
            //    System.Threading.Thread.Sleep(500);
            //}
            if (this.NewMember != "")
            {
                StringBuilder strb= new StringBuilder();
                strb.AppendLine("^XA");
                strb.AppendLine("^LL350");//^FS
                strb.AppendLine("^PW930");//^FS
                strb.AppendLine("^FO20,30");
                strb.AppendLine("^AQ,80,80");
                strb.AppendLine(string.Format(CultureInfo.InvariantCulture, "^FD{0}^FS", this.NewMember));
                strb.AppendLine("^FO20,150");
                strb.AppendLine("^AQ,50,50");
                strb.AppendLine(string.Format(CultureInfo.InvariantCulture, "^FD{0}^FS", this.PickUpTime));
             
                strb.AppendLine("^FO240,150");
                strb.AppendLine("^AQ,50,50");
                strb.AppendLine(string.Format(CultureInfo.InvariantCulture, "^FD{0}^FS", this.Cold));
                //^PQ2= Indicates number of copies to print
                strb.AppendLine(string.Format(CultureInfo.InvariantCulture, "^PQ{0}", "1"));
                //sb1.AppendLine("^PQ2");
                //^XZ=Indicates ending of ZPL page
                strb.AppendLine("^XZ");

                RawPrinterHelper.SendStringToPrinter(printerName, strb.ToString());
            }
        }
    }
For Printing



public class RawPrinterHelper
    {
        // Structure and API declarions:
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
        public class DOCINFOA
        {
            [MarshalAs(UnmanagedType.LPStr)]
            public string pDocName;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pOutputFile;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pDataType;
        }
        [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);

        [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool ClosePrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);

        [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool EndDocPrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool StartPagePrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool EndPagePrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);

        // SendBytesToPrinter()
        // When the function is given a printer name and an unmanaged array
        // of bytes, the function sends those bytes to the print queue.
        // Returns true on success, false on failure.
        public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
        {
            Int32 dwError = 0, dwWritten = 0;
            IntPtr hPrinter = new IntPtr(0);
            DOCINFOA di = new DOCINFOA();
            bool bSuccess = false; // Assume failure unless you specifically succeed.

            di.pDocName = "My C#.NET RAW Document";
            di.pDataType = "RAW";

            // Open the printer.
            if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
            {
                // Start a document.
                if (StartDocPrinter(hPrinter, 1, di))
                {
                    // Start a page.
                    if (StartPagePrinter(hPrinter))
                    {
                        // Write your bytes.
                        bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
                        EndPagePrinter(hPrinter);
                    }
                    EndDocPrinter(hPrinter);
                }
                ClosePrinter(hPrinter);
            }
            // If you did not succeed, GetLastError may give more information
            // about why not.
            if (bSuccess == false)
            {
                dwError = Marshal.GetLastWin32Error();
            }
            return bSuccess;
        }

        public static bool SendFileToPrinter(string szPrinterName, string szFileName)
        {
            // Open the file.
            FileStream fs = new FileStream(szFileName, FileMode.Open);
            // Create a BinaryReader on the file.
            BinaryReader br = new BinaryReader(fs);
            // Dim an array of bytes big enough to hold the file's contents.
            Byte[] bytes = new Byte[fs.Length];
            bool bSuccess = false;
            // Your unmanaged pointer.
            IntPtr pUnmanagedBytes = new IntPtr(0);
            int nLength;

            nLength = Convert.ToInt32(fs.Length);
            // Read the contents of the file into the array.
            bytes = br.ReadBytes(nLength);
            // Allocate some unmanaged memory for those bytes.
            pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
            // Copy the managed byte array into the unmanaged array.
            Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
            // Send the unmanaged bytes to the printer.
            bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
            // Free the unmanaged memory that you allocated earlier.
            Marshal.FreeCoTaskMem(pUnmanagedBytes);
            return bSuccess;
        }
        public static bool SendStringToPrinter(string szPrinterName, string szString)
        {
            IntPtr pBytes;
            Int32 dwCount;
            // How many characters are in the string?
            dwCount = (szString.Length + 1) * Marshal.SystemMaxDBCSCharSize;//szString.Length;
            // Assume that the printer is expecting ANSI text, and then convert
            // the string to ANSI text.
            pBytes = Marshal.StringToCoTaskMemAnsi(szString);
            // Send the converted ANSI string to the printer.
            SendBytesToPrinter(szPrinterName, pBytes, dwCount);
            Marshal.FreeCoTaskMem(pBytes);
            return true;
        }
    }
Call the above functionality using below code:

public void PrintLabel(string strFirstName, string strLastName, string strNoOfCopies, string PickUpTime, string Cold,string NewMember="")
        {
           
            UpcLabel lbl = new UpcLabel(strFirstName, strLastName, strNoOfCopies, PickUpTime, Cold, NewMember);
            //Printer name
            lbl.Print("ZDesigner QLn220 (ZPL)");
         
        }
        public void PrintBarcode(string pProductName,string pLocation,string pNoOfCopies)
        {
            UpcLabel upcLabel = new UpcLabel();
            //Printer name
            upcLabel.PrintBarcode("ZDesigner QLn220 (ZPL)", pProductName, pLocation, pNoOfCopies);
       
        }