Monday, 28 December 2015

C#.Net code slipts

(1)Regular expression for identify the word in sentence and replace that to another word 
===============================================================

Regex.Replace(SpecialityContent.ToLower(), Speciality.ToLower(), builderForSpeciality)

(2)Switch case
===============================================================

switch (mmCityId)
            {
                case LocationApplicableForMedmantraRegions.HyderabadLocationId:
                    regionId = MedMantraRegionId.HyderabadRegionId;
                    break;

                case LocationApplicableForMedmantraRegions.ChennaiLocationId:
                    regionId = MedMantraRegionId.ChennaiRegionId;
                    break;

                case LocationApplicableForMedmantraRegions.KolkattaLocationId:
                    regionId = MedMantraRegionId.KolkattaRegionId;
                    break;

                case LocationApplicableForMedmantraRegions.DelhiLocationId:
                    regionId = MedMantraRegionId.DelhiRegionId;
                    break;

                case LocationApplicableForMedmantraRegions.MumbaiLocationId:
                    regionId = MedMantraRegionId.MumbaiRegionId;
                    break;

                case LocationApplicableForMedmantraRegions.BhubaneshwarLocationId:
                    regionId = MedMantraRegionId.BhubaneshwarRegionId;
                    break;

                case LocationApplicableForMedmantraRegions.ClinicLocationId:
                    regionId = MedMantraRegionId.ClinicRegionId;
                    break;

                case LocationApplicableForMedmantraRegions.BangloreLocationId:
                    regionId = MedMantraRegionId.BangloreRegionId;
                    break;
            }

(3)Enum
================================================================

public enum GenderEnum
    {
        Male,
        Female,
        UnKnown
    }

 public class DoctorProfileModel
    {
        public TransDoctorProfile doctorProfile { set; get; }

        public GenderEnum gender { get; set; }
    }

 private void SetGender(DoctorProfileModel model)
        {
            if (model == null)
                return;

            if (model.doctorProfile.DoctorInfo.gender == GenderConstants.Male)
            {
                model.gender = GenderEnum.Male;
                return;
            }
            if (model.doctorProfile.DoctorInfo.gender == GenderConstants.Female)
            {
                model.gender = GenderEnum.Female;
            }
            if (model.doctorProfile.DoctorInfo.gender == GenderConstants.UnKnown)
            {
                model.gender = GenderEnum.UnKnown;
            }
        }

(4)Regular expression for replace special characters
=======================================================================

 private string getWithoughSpecialityCharacetrs(string text, bool isSpeciality)
        {
            Regex re = new Regex("[;\\/:*?\"<>|&']");
            string textvarialble = text;
            if (!string.IsNullOrEmpty(textvarialble))
            {
                textvarialble = textvarialble.Replace(" ", "-");
                if (isSpeciality)
                    textvarialble = textvarialble.Replace("&", "and");
                textvarialble = textvarialble.Replace(".", "");
                textvarialble = re.Replace(textvarialble, "-");
            }
            return textvarialble.ToLower();
        }

Thursday, 15 October 2015

sql query techniques( inner join in update,Trigger,Capitalise the word first letter,get all procedures created and modified dates)

(1)Inner join while update table records
================================================================

UPDATE im
SET  im.keyword = gm.keyword
FROM  lkp_specialitiesinfo im
INNER JOIN doctors gm ON im.SpecialityId=gm.SpecialityId
WHERE gm.keyword is not null and gm.SpecialityId not  like '%,%'

(2)Curssor
================================================================

-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[RProc_GetDoctorSlootsTimesStartEndTimesByDocId] --628485
@UserId int
AS
BEGIN
DECLARE @DOCTORID INT

DECLARE DOCTORCURSOR CURSOR FOR SELECT UserId FROM Doctors where HasConsultaionDates=1 AND HasActiveSlots=1
AND UserId in(@UserId)
OPEN DOCTORCURSOR
FETCH NEXT FROM DOCTORCURSOR INTO @DOCTORID
WHILE (@@FETCH_STATUS=0)                                      
BEGIN

FETCH NEXT FROM DOCTORCURSOR INTO @DOCTORID
END
CLOSE DOCTORCURSOR                                      
DEALLOCATE DOCTORCURSOR
END

(3)Capitalist word first letter
=======================================================================

CREATE FUNCTION [dbo].[InitCap] ( @InputString varchar(4000) )
RETURNS VARCHAR(4000)
AS
BEGIN

DECLARE @Index          INT
DECLARE @Char           CHAR(1)
DECLARE @PrevChar       CHAR(1)
DECLARE @OutputString   VARCHAR(255)

SET @OutputString = LOWER(@InputString)
SET @Index = 1

WHILE @Index <= LEN(@InputString)
BEGIN
    SET @Char     = SUBSTRING(@InputString, @Index, 1)
    SET @PrevChar = CASE WHEN @Index = 1 THEN ' '
                         ELSE SUBSTRING(@InputString, @Index - 1, 1)
                    END

    IF @PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(')
    BEGIN
        IF @PrevChar != '''' OR UPPER(@Char) != 'S'
            SET @OutputString = STUFF(@OutputString, @Index, 1, UPPER(@Char))
    END

    SET @Index = @Index + 1
END

RETURN @OutputString

END


(4) Read XML Data
=======================================================================

 ALTER PROCEDURE [dbo].[Proc_Insert_BatchData]          
(                    
@XMLBatchData XML                    
)                    
AS                    
BEGIN              
               
INSERT INTO trans_Dataloaderbatchdata (BatchId,SiteName,SiteId,VisitName,VisitId,SubjectName,          
SubjectId,PageName,PageId,ItemId,ItemName,ItemValue,PanelId,CycleId,TrialId,StatusId,  
--CreatedBy,CreatedIp,GeneratedControlName,Rownum,Colnum,PreviousItemValue)                    
CreatedBy,CreatedIp,GeneratedControlName,Rownum,Colnum)
SELECT T.Item.query('./BatchId').value('.', 'INT') BatchId,            
T.Item.query('./SiteName').value('.', 'VARCHAR(100)') SiteName,                    
T.Item.query('./SiteId').value('.', 'INT') SiteId,            
T.Item.query('./VisitName').value('.', 'VARCHAR(100)') VisitName,                
T.Item.query('./VisitId').value('.', 'INT') VisitId,          
T.Item.query('./SubjectName').value('.', 'VARCHAR(100)') SubjectName,                    
T.Item.query('./SubjectId').value('.', 'INT') SubjectId  ,          
T.Item.query('./PageName').value('.', 'VARCHAR(100)') PageName,          
T.Item.query('./PageId').value('.', 'INT') PageId  ,              
T.Item.query('./ItemId').value('.', 'INT') ItemId  ,              
T.Item.query('./ItemName').value('.', 'VARCHAR(500)') ItemName  ,            
T.Item.query('./ItemValue').value('.', 'VARCHAR(500)') ItemValue  ,      
T.Item.query('./PanelId').value('.', 'INT') PanelId  ,        
T.Item.query('./CycleId').value('.', 'INT') CycleId  ,      
T.Item.query('./TrialId').value('.', 'INT') TrialId  ,          
T.Item.query('./StatusId').value('.', 'INT') StatusId  ,          
T.Item.query('./CreatedBy').value('.', 'INT') CreatedBy   ,              
T.Item.query('./CreatedIP').value('.', 'VARCHAR(50)') CreatedIP  ,    
T.Item.query('./GeneratedControlName').value('.', 'VARCHAR(500)') GeneratedControlName,  
T.Item.query('./Rownum').value('.', 'VARCHAR(50)') Rownum  ,    
T.Item.query('./Colnum').value('.', 'VARCHAR(50)') Colnum
--, T.Item.query('./PreviousItemValue').value('.', 'VARCHAR(500)') PreviousItemValue
FROM @XMLBatchData.nodes('/Rows/Row') AS T(Item)                    
RETURN 0                    

END    

(5)Dynamic sql
================================================================

DECLARE @dynSql NVARCHAR(max)

set @dynSql='                              
  Insert into '+ @PanelTable + ' (TrialId, SiteId, CycleId,  VisitId, PageId, PanelId, SubjectId,RowNum,CreatedBy,CreatedOn,
  CreatedIP,VisitNo,VisitCode,CreatedSiteTime,'+@ItemColumns+')                                      
  values( '+ Convert(varchar(20),@TrialId)+','+Convert(varchar(20),@SiteId)+','+Convert(varchar(20),@CycleId)+','+Convert(varchar(20),@VisitId)+',
  '+Convert(varchar(20),@PageId)+','+Convert(varchar(20),@PenelId)+','+Convert(varchar(20),@SubjectId)+','+Convert(varchar(20),@RowNo)+',
  '+Convert(varchar(20),@userid)+',getdate(),'''+Convert(varchar(100),@CreatedIP)+''','''+Convert(varchar(100),@VisitNo)+''',
  '''+Convert(varchar(100),@VisitCode)+''',dbo.fn_GetSiteTime('+Convert(varchar(20),@SiteId)+'),'+@ItemValues+')'

EXEC sp_executesql @dynSql

(6)Triggers after insert and after update
=================================================================

ALTER TRIGGER [dbo].[InsertDoctorInfoOnDoctor] ON [dbo].[DoctorDetails]
FOR INSERT
AS
DECLARE @USERID AS INT=0
select @USERID=i.UserId from inserted i;
IF(@USERID!='0')
BEGIN
END

ALTER TRIGGER [dbo].[UpdateDoctorInfoOnDoctor] ON [dbo].[DoctorDetails]
FOR UPDATE
AS
DECLARE @USERID AS INT=0
select @USERID=i.UserId from inserted i;
IF(@USERID!='0')
BEGIN


END

(7)Query Performance
=====================================================================

SET @LowerBand  = (@CurrentPage - 1) * @PageSize
SET @UpperBand  = (@CurrentPage * @PageSize) + 1
WITH tempProfile AS(
SELECT
[dbo].[ICUsersAppointmentsInfo_Report].[ICAppointmentId] AS ICAppointmentId,
ROW_NUMBER() OVER (ORDER BY [dbo].[ICUsersAppointmentsInfo_Report].[AutoId] DESC) AS RowNumber    
FROM [dbo].[ICUsersAppointmentsInfo_Report]
where [dbo].[ICUsersAppointmentsInfo_Report].[HospitalId]=1
)

SELECT * FROM  tempProfile WHERE  RowNumber > CONVERT(VARCHAR,@LowerBand) AND RowNumber < CONVERT(VARCHAR, @UpperBand)


(8)Get procedures created date and modifies dates
=====================================================================
select name,create_date,modify_date
from sys.procedures
order by create_date desc

(9)Generate Class from database table
=====================================================================

declare @TableName sysname = 'TableName'
declare @Result varchar(max) = 'public class ' + @TableName + '
{'

select @Result = @Result + '
    public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }
'
from
(
    select
        replace(col.name, ' ', '_') ColumnName,
        column_id ColumnId,
        case typ.name
            when 'bigint' then 'long'
            when 'binary' then 'byte[]'
            when 'bit' then 'bool'
            when 'char' then 'string'
            when 'date' then 'DateTime'
            when 'datetime' then 'DateTime'
            when 'datetime2' then 'DateTime'
            when 'datetimeoffset' then 'DateTimeOffset'
            when 'decimal' then 'decimal'
            when 'float' then 'float'
            when 'image' then 'byte[]'
            when 'int' then 'int'
            when 'money' then 'decimal'
            when 'nchar' then 'string'
            when 'ntext' then 'string'
            when 'numeric' then 'decimal'
            when 'nvarchar' then 'string'
            when 'real' then 'double'
            when 'smalldatetime' then 'DateTime'
            when 'smallint' then 'short'
            when 'smallmoney' then 'decimal'
            when 'text' then 'string'
            when 'time' then 'TimeSpan'
            when 'timestamp' then 'DateTime'
            when 'tinyint' then 'byte'
            when 'uniqueidentifier' then 'Guid'
            when 'varbinary' then 'byte[]'
            when 'varchar' then 'string'
            else 'UNKNOWN_' + typ.name
        end ColumnType,
        case
            when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier')
            then '?'
            else ''
        end NullableSign
    from sys.columns col
        join sys.types typ on
            col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
    where object_id = object_id(@TableName)
) t
order by ColumnId

set @Result = @Result  + '
}'

print @Result

Saturday, 10 October 2015

Asp.Net Fileupload along with validations save in folder, database in binary format along with thumb nail

(1)Javascript to validate fileformate
=============================================================
<script src="Scripts/jquery-1.7.1.js"></script>
    <script type="text/javascript">
        function ValidateFile() {
            var fileControlValue = document.getElementById("<%=fileUpload.ClientID%>").value;
            var msg = "Please Fille the bellow missing fields";
            var isFocus = false;
            if (fileControlValue == "" || fileControlValue == null) {
                msg = msg + "\n -Select the file";
                if (isFocus == false) {
                    document.getElementById("<%=fileUpload.ClientID%>").focus();
                }
            }
            if (msg != "Please Fille the bellow missing fields") {
                alert(msg);
                return false;
            }
            else {
                if (!validateFileFormate()) {
                    alert("Invalid file formate.File formate must be .doc,.jpg,.png,.docx,.xls");
                    return false;
                }
            }
            return true;
        }
        function validateFileFormate() {
            var fileControlValue = document.getElementById("<%=fileUpload.ClientID%>").value;
            var docType = fileControlValue.substr(fileControlValue.lastIndexOf('.'), fileControlValue.Length);
            var allowFileType = new Array(".doc", ".jpg", ".png", ".docx", ".xls", ".xlsx");
            if (allowFileType.indexOf(docType) > -1) {
                return true;
            }
            return false;
        }
    </script>

(2)Save file in folder
========================================================

string filePath = Server.MapPath("~") + ConfigurationManager.AppSettings["FilesPath"];
                string fileName = fileUpload.FileName;
                string fileType = fileName.Substring(fileName.LastIndexOf("."));
                string targetFilePath = string.Empty;
                targetFilePath = filePath + fileName.Substring(0, fileUpload.FileName.LastIndexOf(".")) + DateTime.Now.GetHashCode() + fileType;
                FileDetails.CreateBy = 1;
                FileDetails.FileName = fileName;
                FileDetails.FilePath = targetFilePath;
                FileDetails.FileType = fileType;

                fileUpload.PostedFile.SaveAs(targetFilePath);

(3)Save file in database in binary formate along with thumb nail
================================================================

                string fileName = fileUpload.FileName;
                string fileType = fileName.Substring(fileName.LastIndexOf("."));
                FileDetails.CreateBy = 1;
                FileDetails.FileName = fileName;
                FileDetails.FilePath = CreateThumbNail();
                FileDetails.FileType = fileType;
                FileDetails.FileBinaryData = ConvertToBinaryFormate(FileDetails.FilePath);
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connectionstring"].ToString());
                SqlCommand cmd = new SqlCommand("SP_INSERTFILEINFO", con);
                cmd.CommandType = CommandType.StoredProcedure;
                con.Open();
                cmd.Parameters.AddWithValue("@FileName", FileDetails.FileName);
                cmd.Parameters.AddWithValue("@FileType", FileDetails.FileType);
                cmd.Parameters.AddWithValue("@FilePath", FileDetails.FilePath);
                cmd.Parameters.AddWithValue("@FileBinaryData", FileDetails.FileBinaryData);
                cmd.Parameters.AddWithValue("@CreateBy", FileDetails.CreateBy);
                cmd.Parameters.AddWithValue("@IDVALUE", "");

                int output = cmd.ExecuteNonQuery();
                con.Close();

 protected byte[] ConvertToBinaryFormate(string filePath)
    {
        byte[] img=new byte[5];
        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        img = new byte[fs.Length];
        fs.Read(img, 0, (int)fs.Length);
        fs.Close();
        return img;
    }

 protected bool ThumbnailCallback()
    {
        return true;
    }
protected string CreateThumbNail()
    {
        string filePath = Server.MapPath("~") + ConfigurationManager.AppSettings["FilesPath"];
        string fileName = fileUpload.FileName;
        string fileType = fileName.Substring(fileName.LastIndexOf("."));
        string targetFilePath = string.Empty;
        targetFilePath = filePath + fileName.Substring(0, fileName.LastIndexOf(".")) + DateTime.Now.GetHashCode() + fileType;
        string Destination = filePath + fileName.Substring(0, fileName.LastIndexOf(".")) + DateTime.Now.GetHashCode() + "Tumb" + fileType;
        if (!Directory.Exists(filePath))
        {
            Directory.CreateDirectory(filePath);
        }
        fileUpload.PostedFile.SaveAs(targetFilePath);

        System.Drawing.Image objImage = System.Drawing.Image.FromFile(targetFilePath);
        System.Drawing.Imaging.ImageFormat imgFormat = objImage.RawFormat;

        int newImageHeight = objImage.Height;
        int newImageWidth = objImage.Width;

        int targetImageHeight = 100;
        int targetImageWidth = 150;


        if (targetImageHeight > 100 || targetImageWidth > 100)
        {
            targetImageHeight = 100;
            targetImageWidth = 100;
        }

        if (newImageHeight > targetImageHeight || newImageWidth > targetImageWidth)
        {
            if (newImageWidth * (targetImageHeight / targetImageWidth) > newImageHeight)
            {

                newImageHeight = (targetImageWidth * newImageHeight) / newImageWidth;
                newImageWidth = targetImageWidth;
            }
            else
            {
                newImageWidth = (targetImageHeight * newImageWidth) / newImageHeight;
                newImageHeight = targetImageHeight;
            }
        }
        System.Drawing.Image myThumbNail = new System.Drawing.Bitmap(newImageWidth, newImageHeight, objImage.PixelFormat);
        myThumbNail = objImage.GetThumbnailImage(newImageWidth, newImageHeight,new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
        myThumbNail.Save(Destination);
        objImage.Dispose();
        myThumbNail.Dispose();
        return Destination;
    }

(4)Web.config
=======================================================
 <add key="FilesPath" value='UploadedFike\'/>

Friday, 9 October 2015

Asp.Net Concepts(Master page,cookies,cache)

Reference ASP.NET Master Page Content
===================================================
(1)Add this tage in .aspx


<%@ MasterType virtualpath="~/Masters/Master1.master" %>

void Page_Load()
{
    // Gets a reference to a TextBox control inside 
    // a ContentPlaceHolder
    ContentPlaceHolder mpContentPlaceHolder;
    TextBox mpTextBox;
    mpContentPlaceHolder = 
      (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
    if(mpContentPlaceHolder != null)
    {
        mpTextBox = 
            (TextBox) mpContentPlaceHolder.FindControl("TextBox1");
        if(mpTextBox != null)
        {
            mpTextBox.Text = "TextBox found!";
        }
    }
    
    // Gets a reference to a Label control that not in 
    // a ContentPlaceHolder
    Label mpLabel = (Label) Master.FindControl("masterPageLabel");
    if(mpLabel != null)
    {
        Label1.Text = "Master page label = " + mpLabel.Text;
    }
}
(2)Adding cookie and read cookie
===================================================================
(a)Add cookie
=============
Response.Cookies.Remove("HomeSpecialtyorDoctorSearch");
HttpCookie cookie = new HttpCookie("HomeSpecialtyorDoctorSearch");
Response.Cookies.Add(cookie);
cookie.Values.Add("CityId", ddlCity.SelectedValue);
cookie.Values.Add("CityName", ddlCity.SelectedItem.Text);
(b)Read cookie
===============
HttpCookie cookie = Request.Cookies.Get("HomeSpecialtyorDoctorSearch");
        if (cookie.Values["CityId"] != null)
        {
                appointmentTypeId = Convert.ToInt32(cookie.Values["CityId"]);
        }

(3)Cache 
===========================================================
(a)Add cache
=============
if (HttpRuntime.Cache["HospitalsDataDDl"] == null)
        {
            hospitalList = _GetTransactionData.GetHospitalInformation();
            if (hospitalList.Count > 0)
            {
                HttpRuntime.Cache["HospitalsDataDDl"] = hospitalList;
            }
        }
        else
        {
            hospitalList = (List<RHospitalBO>)HttpRuntime.Cache["HospitalsDataDDl"];
        }
(b)Remove cache
=================
HttpRuntime.Cache.Remove("HospitalsDataDDl");

Sunday, 4 October 2015

Sending an email with asp.net

(1)Sending Email with normal text along with attachment
==================================================================
==================================================================
(i)UI page
=========================
 <table border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td style="width: 80px">
            To:
        </td>
        <td>
            <asp:TextBox ID="txtTo" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            Subject:
        </td>
        <td>
            <asp:TextBox ID="txtSubject" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td valign = "top">
            Body:
        </td>
        <td>
            <asp:TextBox ID="txtBody" runat="server" TextMode = "MultiLine" Height = "150" Width = "200"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            File Attachment:
        </td>
        <td>
            <asp:FileUpload ID="fuAttachment" runat="server" />
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            Gmail Email:
        </td>
        <td>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            Gmail Password:
        </td>
        <td>
            <asp:TextBox ID="txtPassword" runat="server" TextMode = "Password"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
        </td>
        <td>
            <asp:Button Text="Send" OnClick="SendEmail" runat="server" />
        </td>
    </tr>
</table>
(ii).aspx.cs page
===================
using (MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text))
        {
            mm.Subject = txtSubject.Text;
            mm.Body = txtBody.Text;
            if (fuAttachment.HasFile)
            {
                string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
                mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
            }
            mm.IsBodyHtml = false;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = NetworkCred;
            smtp.Port = 587;
            smtp.Send(mm);
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
        }

Note: by using this we can face one issue "

The server response was: 5.5.1 Authentication Required in ASP.Net Application." issue this is because of  gmail security. to over come this and from email should not have any 2 step verification code.

Once you visit the link you need to modify the Less Secure Apps setting and Turn On access to Less Secure Apps as shown below.
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required

Saturday, 3 October 2015

Asp.net State management

 There are two types of state management system in ASP.NET.
- Client-side state management
- Server-side state management

Explain client side state management system.

ASP.NET provides several techniques for storing state information on the client. These include the following:
view state ASP.NET uses view state to track values in controls between page requests. It works within the page only. You cannot use view state value in next page.
control state: You can persist information about a control that is not part of the view state. If view state is disabled for a control or the page, the control state will still work.
hidden fields: It stores data without displaying that control and data to the user’s browser. This data is presented back to the server and is available when the form is processed. Hidden fields data is available within the page only (page-scoped data).
Cookies:Cookies are small piece of information that server creates on the browser. Cookies store a value in the user’s browser that the browser sends with every page request to the web server.
Query strings: In query strings, values are stored at the end of the URL. These values are visible to the user through his or her browser’s address bar. Query strings are not secure. You should not send secret information through the query string.

Explain server side state management system.

The following objects are used to store the information on the server:
- Application State:
This object stores the data that is accessible to all pages in a given Web application. The Application object contains global variables for your ASP.NET application.
- Cache Object: Caching is the process of storing data that is used frequently by the user. Caching increases your application’s performance, scalability, and availability. You can catch the data on the server or client.
- Session State: Session object stores user-specific data between individual requests. This object is same as application object but it stores the data about particular user.

Explain cookies with example.

A cookie is a small amount of data that server creates on the client. When a web server creates a cookie, an additional HTTP header is sent to the browser when a page is served to the browser. The HTTP header looks like this:
Set-Cookie: message=Hello. After a cookie has been created on a browser, whenever the browser requests a page from the same application in the future, the browser sends a header that looks like this:
Cookie: message=Hello
Cookie is little bit of text information. You can store only string values when using a cookie. There are two types of cookies:
- Session cookies
- Persistent cookies.
A session cookie exists only in memory. If a user closes the web browser, the session cookie delete permanently.
A persistent cookie, on the other hand, can available for months or even years. When you create a persistent cookie, the cookie is stored permanently by the user’s browser on the user’s computer.
Creating cookie
protected void btnAdd_Click(object sender, EventArgs e)
{
    Response.Cookies[“message”].Value = txtMsgCookie.Text;
}
// Here txtMsgCookie is the ID of TextBox. 
// cookie names are case sensitive. Cookie named message is different from setting a cookie named Message.
The above example creates a session cookie. The cookie disappears when you close your web browser. If you want to create a persistent cookie, then you need to specify an expiration date for the cookie.
Response.Cookies[“message”].Expires = DateTime.Now.AddYears(1);
Reading Cookies
void Page_Load()
{
if (Request.Cookies[“message”] != null)
lblCookieValue.Text = Request.Cookies[“message”].Value;
}
// Here lblCookieValue is the ID of Label Control.

Cookies with keyvalue pair
HttpCookie cookie = new HttpCookie("CookieName");
cookie.Values["key1"] = "value1";
cookie.Values["key2"] = "value2";
Response.Cookies.Add(cookie);

Describe the disadvantage of cookies.

- Cookie can store only string value.
- Cookies are browser dependent.
- Cookies are not secure.
- Cookies can store small amount of data.

What is Session object? Describe in detail.

HTTP is a stateless protocol; it can't hold the user information on web page. If user inserts some information, and move to the next page, that data will be lost and user would not able to retrieve the information. For accessing that information we have to store information. Session provides that facility to store information on server memory. It can support any type of object to store. For every user Session data store separately means session is user specific.
Storing the data in Session object.
Session [“message”] = “Hello World!”;
Retreving the data from Session object.
Label1.Text = Session[“message”].ToString();

What are the Advantages and Disadvantages of Session?

Following are the basic advantages and disadvantages of using session.
Advantages:
- It stores user states and data to all over the application.
- Easy mechanism to implement and we can store any kind of object.
- Stores every user data separately.
- Session is secure and transparent from user because session object is stored on the server.
Disadvantages:
- Performance overhead in case of large number of user, because of session data stored in server memory.
- Overhead involved in serializing and De-Serializing session Data. Because In case of StateServer and SQLServer session mode we need to serialize the object before store.

Explain Cache
===========================================================================
ASP.NET provides two types of caching that you can use to create high-performance Web applications. 

The first is output caching, which allows you to store dynamic page and user control responses on any HTTP 1.1 cache-capable device in the output stream, from the originating server to the requesting browser. 

The second type of caching is application data caching, which you can use to programmatically store arbitrary objects, such as application data, in server memory so that your application can save the time and resources it takes to recreate them.

Caching is implemented by the Cache class, with cache instances private to each application. The cache lifetime is tied to that of the application; when the application is restarted, the Cache object is recreated.

Add Items to the Cache


 If you use the Insert method to add an item to the cache and an item with the same name already exists, the existing item in the cache is replaced.

 if you use the Add method and an item with the same name already exists in the cache, the method will not replace the item and will not raise an exception.

WCF Service with JSON formate both service and client

(A)Service
=======================================================================
=======================================================================

(1)ServiceContract
========================================================================

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace JsonFormate
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "/GetAllCustomersJson")]
        List<Customer> GetAllCustomersJson();

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "/GetAllCustomersSoap")]
        List<Customer> GetAllCustomersSoap();

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "/GetCustomersJson")]
        Customer GetCustomersJson();

        [OperationContract]
        //[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "/GetAllCustomersDynamicSerialization")]
        string GetAllCustomersDynamicSerialization();
   
    }


    [DataContract]
    public class Customer
    {
        [DataMember]
        public int CustomerId { get; set; }

        [DataMember]
        public string CustomerName { get; set; }

        [DataMember]
        public string CustomerMobile { get; set; }

        [DataMember]
        public DateTime CustomerDob { get; set; }

        [DataMember]
        public List<Address> Address { get; set; }

    }
    [DataContract]
    public class Address
    {
        [DataMember]
        public string Lan1 { get; set; }

        [DataMember]
        public BillingAddress BAddress { get; set; }

        [DataMember]
        public ShippingAddress SAddress { get; set; }
    }

    [DataContract]
    public class BillingAddress
    {
        [DataMember]
        public string Blan1 { get; set; }

        [DataMember]
        public string Blan2 { get; set; }

    }

    [DataContract]
    public class ShippingAddress
    {
        [DataMember]
        public string Slan1 { get; set; }

        [DataMember]
        public string Slan2 { get; set; }
    }
}

(2)Service implementer
===================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace JsonFormate
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {
        public readonly List<Customer> _customerList;
        public Service1()
        {
            _customerList = new List<Customer>(){
               new Customer{
                   CustomerId=1,
                   CustomerName="Das",
                   CustomerMobile="8500014303",
                   CustomerDob=DateTime.Now,
                   Address=new List<Address>(){
                       new Address(){
                           Lan1="Lan1",
                           BAddress=new BillingAddress{
                               Blan1="BLan1",
                               Blan2="BLan2"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan1",
                               Slan2="Slan2"
                           }
                       },
                       new Address(){
                           Lan1="Lan11",
                           BAddress=new BillingAddress{
                               Blan1="BLan11",
                               Blan2="BLan21"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan11",
                               Slan2="Slan21"
                           }
                       }
                   }
               },
                new Customer{
                   CustomerId=1,
                   CustomerName="Das",
                   CustomerMobile="8500014303",
                   CustomerDob=DateTime.Now,
                   Address=new List<Address>(){
                       new Address(){
                           Lan1="Lan1",
                           BAddress=new BillingAddress{
                               Blan1="BLan1",
                               Blan2="BLan2"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan1",
                               Slan2="Slan2"
                           }
                       },
                       new Address(){
                           Lan1="Lan11",
                           BAddress=new BillingAddress{
                               Blan1="BLan11",
                               Blan2="BLan21"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan11",
                               Slan2="Slan21"
                           }
                       }
                   }
               },
                new Customer{
                   CustomerId=1,
                   CustomerName="Das",
                   CustomerMobile="8500014303",
                   CustomerDob=DateTime.Now,
                   Address=new List<Address>(){
                       new Address(){
                           Lan1="Lan1",
                           BAddress=new BillingAddress{
                               Blan1="BLan1",
                               Blan2="BLan2"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan1",
                               Slan2="Slan2"
                           }
                       },
                       new Address(){
                           Lan1="Lan11",
                           BAddress=new BillingAddress{
                               Blan1="BLan11",
                               Blan2="BLan21"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan11",
                               Slan2="Slan21"
                           }
                       }
                   }
               },
                new Customer{
                   CustomerId=1,
                   CustomerName="Das",
                   CustomerMobile="8500014303",
                   CustomerDob=DateTime.Now,
                   Address=new List<Address>(){
                       new Address(){
                           Lan1="Lan1",
                           BAddress=new BillingAddress{
                               Blan1="BLan1",
                               Blan2="BLan2"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan1",
                               Slan2="Slan2"
                           }
                       },
                       new Address(){
                           Lan1="Lan11",
                           BAddress=new BillingAddress{
                               Blan1="BLan11",
                               Blan2="BLan21"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan11",
                               Slan2="Slan21"
                           }
                       }
                   }
               },
                new Customer{
                   CustomerId=1,
                   CustomerName="Das",
                   CustomerMobile="8500014303",
                   CustomerDob=DateTime.Now,
                   Address=new List<Address>(){
                       new Address(){
                           Lan1="Lan1",
                           BAddress=new BillingAddress{
                               Blan1="BLan1",
                               Blan2="BLan2"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan1",
                               Slan2="Slan2"
                           }
                       },
                       new Address(){
                           Lan1="Lan11",
                           BAddress=new BillingAddress{
                               Blan1="BLan11",
                               Blan2="BLan21"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan11",
                               Slan2="Slan21"
                           }
                       }
                   }
               }
           };
         }
        public List<Customer> GetAllCustomersJson()
        {
            return _customerList;
        }

        public List<Customer> GetAllCustomersSoap()
        {
            return _customerList;
        }


        public Customer GetCustomersJson()
        {
            return new Customer
              {
                  CustomerId = 1,
                  CustomerName = "Das",
                  CustomerMobile = "8500014303"
              };
        }


        public string GetAllCustomersDynamicSerialization()
        {
            DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(List<Customer>));
            MemoryStream ms = new MemoryStream();
            js.WriteObject(ms, _customerList);
         
            ms.Position = 0;
            StreamReader sr = new StreamReader(ms);
            string data123 = sr.ReadToEnd();
            sr.Close();
            ms.Close();
            return data123;
        }
    }
}
(3)Wb.config 
==================================================================
<?xml version="1.0"?>
<configuration>

  <connectionStrings>
    <add name="WcfNorthWindConnectionString" connectionString="Data Source=Dasu;Initial Catalog=WcfNorthWind;User ID=sa;Password=anandarao67"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1"/>
  </system.web>
  <system.serviceModel>
    <services>
      <service name="JsonFormate.Service1" behaviorConfiguration="ServiceBehaviour">
        <!-- Service Endpoints -->
        <!-- Unless fully qualified, address is relative to base address supplied above -->
        <endpoint address="" binding="webHttpBinding" contract="JsonFormate.IService1" behaviorConfiguration="Web">
          <!-- 
              Upon deployment, the following identity element should be removed or replaced to reflect the 
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity 
              automatically.
          -->
        </endpoint>
       <endpoint address="soap" binding="basicHttpBinding" contract="JsonFormate.IService1"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
           <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    <endpointBehaviors>
      <behavior name="Web">
        <webHttp/>
      </behavior>
    </endpointBehaviors>
    </behaviors>
    <standardEndpoints>
      <webScriptEndpoint>
      <standardEndpoint name="" crossDomainScriptAccessEnabled="true" />
      </webScriptEndpoint>
    </standardEndpoints>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
 <modules runAllManagedModulesForAllRequests="true" />
 <httpProtocol>
 <customHeaders>
 <add name="Access-Control-Allow-Origin" value="*" />
 <add name="Access-Control-Allow-Headers" value="Content-Type" /> 
 </customHeaders>
 </httpProtocol> 
</system.webServer>

</configuration>
(B)Client call service from jquery
=======================================================================
=======================================================================
Note: only json return type will work in jquery ajax call

 <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                url: "http://localhost:49931/Service1.svc/GetAllCustomersJson"
            }).then(function (data) {
                alert(data);
            });
        });
    </script>

(C)Client call service from .aspx.cs
=====================================================================
=====================================================================
(I)Json type with webmethod attribute
=================
 HttpClient client1 = new HttpClient();
        HttpResponseMessage wcfResponse = client1.GetAsync("http://localhost:49931/Service1.svc/GetAllCustomersJson").Result;
        HttpContent stream = wcfResponse.Content;
        var data = stream.ReadAsStringAsync();
        var data1 = data.Result;

(ii)Normal call
===================
Service1Client client2 = new Service1Client();
        var responce = client2.GetAllCustomersJson();
(iii)Json type with out webmethod attribute
==================
string  ms = client2.GetAllCustomersDynamicSerialization();
(iv)Xml type
==================
HttpClient client1 = new HttpClient();
        HttpResponseMessage wcfResponse = client1.GetAsync("http://localhost:49931/Service1.svc/GetAllCustomersSoap").Result;
        HttpContent stream = wcfResponse.Content;
        var data = stream.ReadAsStringAsync();
        var data1 = data.Result;

(D)Client web.config
==================
<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IService1" />
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:49931/Service1.svc/soap"
        binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1"
        contract="ServiceReference1.IService1" name="BasicHttpBinding_IService1" />
    </client>
  </system.serviceModel>

Wednesday, 23 September 2015

Jquery Date picker for all devices( desktop,Android, Note Pad,Ios devices),radiobutton lick events

Date picker for all devices


======================================================================
<html>

<head>

<meta charset="UTF-8" />

<title>datepicker-i</title>

<meta http-equiv="X-UA-Compatible" content="IE=9;FF=3;chrome=1;OtherUA=4" />

<meta name="viewport" content="width=200, user-scalable=no" />

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.js"></script>

<script type="text/javascript">

$(function () {

$("#date").datepicker({

defaultDate: "+1w",

showAnim: false,

maxDate: "+0d",

changeMonth: true,

changeYear: true,

yearRange: "-150:+0"

}).focus(function () {

$(this).blur()

});

})

</script>

<style type="text/css">

.ui-datepicker{font-size:50%}

</style>

</head>

<body>

<input type="text" id="date" name="date" value="">

</body>

</html>











<script type="text/javascript">

        $(document).ready(function () {

         

            $("#rdoIndia").click(function () {

                //$("#content").html(indiaData);

                $("#indiaContent").attr("style","display:block");

                $("#chinaContent").attr("style", "display:none");

                $("#usaContent").attr("style", "display:none");

            });

            $("#rdoUsa").click(function () {

                $("#indiaContent").attr("style","display:none");

                $("#chinaContent").attr("style", "display:none");

                $("#usaContent").attr("style", "display:block");

            });

            $("#rdoChina").click(function () {

                $("#indiaContent").attr("style","display:none");

                $("#chinaContent").attr("style", "display:block");

                $("#usaContent").attr("style", "display:none");

            });

        });

    </script>


<div>
    <input type="radio" name="country" id="rdoIndia"/>India
    <input type="radio" name="country" id="rdoChina"/>Chain
    <input type="radio" name="country" id="rdoUsa"/>Usa
        <div id="indiaContent" style="display:none">
            india
        </div>
         <div id="chinaContent" style="display:none">
            china
        </div>
         <div id="usaContent" style="display:none">
            usa
        </div>
    </div>