Wednesday, August 20, 2014

Working with Pivot and UnPivot in Sql server

I was working with one of my project, I have to convert rows to columns and columns to rows from the SQL server .we can use PIVOT AND UNPIVOT in SQL server to convert rows to columns and columns to rows. I would like to share you guys how to use PIVOT AND UNPIVOT in real time scenario.

-- #############################################################################
-- Using PIVOT to Convert Rows to Columns

-- First, declare a sample table of cars.
declare @cars as table (
car_id tinyint,
attribute varchar(20),
value varchar(20)
)

-- Then, populate that table with some values.
-- Two example cars are being inserted each with its Make, Model, and Color.
insert into @cars(car_id, attribute, value)
values      (1, 'Make', 'VW'),
            (1, 'Model', 'Rabbit'),
            (1, 'Color', 'Gold'),
            (2, 'Make', 'Jeep'),
            (2, 'Model', 'Wrangler'),
            (2, 'Color', 'Gray')


-- Now, PIVOT is used to transform this data from rows to columns.
-- Notice that PIVOT requires an aggregate so be cautious if you
-- are pivoting a result set without using a unique value.
-- Note that hard-coding the list of attributes to pivot is required.
select pvt.car_id, pvt.Make, pvt.Model, pvt.Color
from @cars c
pivot (
min(value)
for attribute in ([Make],[Model],[Color])
) pvt


GO





PIVOT TABLE:


-- #############################################################################
-- Using UNPIVOT to Convert Columns to Rows

-- First, declare a sample table of cars.
declare @cars as table (
car_id tinyint identity(1,1),
make varchar(20),
model varchar(20),
color varchar(20)
)

-- Then, populate that table with some values.
-- Two example cars are being inserted each with its Make, Model, and Color.
insert into @cars(make, model, color)
values      ('VW', 'Rabbit', 'Gold'),
            ('Jeep', 'Wrangler', 'Gray')


-- Now, UNPIVOT is used to swap our columns into rows.
-- Hard-coding the list of columns is necessary as seen with PIVOT.
select unpvt.car_id, unpvt.attribute, unpvt.value
from @cars c
unpivot (
 value
 for attribute in (Make, Model, Color)
) unpvt

select * from @cars

UNPIVOT TABLE:






Friday, August 15, 2014

Using method type post/get in asp.net web form

I  will start the article from with detailed information.


Actually form has two types of in asp.net2.0.
1) Get
2) Post
When working with Get method:
  • We can access all form input variables in the next page which we mentioned in the action attribute.
  • All the submitted information is displayed in the address bar as part of the URL.
  •  Url Which is not secured because values will be shown in address bar
When working with Post method:
  • we can access the variables in the page which we mentioned in the action attribute.
  • we can access those variable as shown below
  • which is more secured, variable not accessible
Now we will have small application with 2 web pages
1)       default.aspx
2)       Webform.aspx
GET:
  • I have given the value for action attribute is webform1.aspx in the default.aspx page with method type
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
   <form action="webform1.aspx" method="get" >
   First name: <input type="text" name="fname" /><br />
   Last name: <input type="text" name="lname" /><br />
   Age: <input type="text" name="age" /><br />
   <input type="submit" value="Submit" />
 </form>
</body>
</html>
  • Variables will be available in the address bar like below .

  • We can access the variables from the Address to Form using Request.QueryString[] like below.
  protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["fname"] != null)
            {
                Response.Write("fname : " + Request.QueryString["fname"] + \n");
            }
            if (Request.QueryString["lname"] != null)
            {
                Response.Write("lname : " + Request.QueryString["lname"] + "");
            }
       }
POST:
  • Variables will be post to the next page  using Post method type
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
   <form action="webform1.aspx" method="post" >
   First name: <input type="text" name="fname" /><br />
   Last name: <input type="text" name="lname" /><br />
   Age: <input type="text" name="age" /><br />
   <input type="submit" value="Submit" />
 </form>
</body>
</html>
  • We cannot access the variables from the url.

  • We can access the variables from the request. Form [].
  protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Form["fname"] != null)
            {
                Response.Write("fname : " + Request.Form["fname"] + "\n");
            }
            if (Request.Form["lname"] != null)
            {
                Response.Write("lname : " + Request.Form["lname"] + "");
            }
        }

How to Deploy Web applications on web server

How to Deploy Web applications on web server

Step1: Right click on solution AddàNew ProjectàSelect Other Project Type under project Types.
Step2: Select Web set up Projects from templates like below.
Step3: Set up project will be added in to your Solution successfully.
Step4: Click on File System Editor from the solution Explorer.
Step5: Expand Web application Folder, right click on bin Folder add Project Output from the web UI Solution.
Step6: Right click on Web application Folder add project output from Content files from the Web UI.
Step7: Rebuild the Solution, install in the same in client machines

Scheduling SSRS Reports from asp.net application:

Scheduling SSRS Reports from asp.net application:

Creating the Web Service Proxy:
To add a proxy class to your project using Wsdl.exe
From a command prompt, use Wsdl.exe to create a proxy class, specifying (at a minimum) the URL to the Report Server Web service. For example, the following command prompt statement specifies a URL for the management endpoint of the Report Server Web service:
Copy :  wsdl /language:CS /n:"Microsoft.SqlServer.ReportingServices2010" http:///reportserver/reportexecution2005.asmx?wsdl
Add Proxy Class to your Project: add this class file to your project which common project in the project. Access this class from data Access layer.
Button clicks Event to save Schedule:
  try
            {
                    ReportSchedule reportschedule = new ReportSchedule();
                    ReportServerCredentials credentials = new ReportServerCredentials();

                    reportschedule.Credentials = credentials.NetworkCredentials;
                    //System.Net.CredentialCache.DefaultCredentials;
                    string eventType = "TimedSubscription";
                    string matchData = GetMatchData();
                    ExtensionSettings extSettings = GetExtensionSettings();
                    // Set the report parameter values.
                    ParameterValue[] parameters = SetReportSubScriptionParameters(strReportParams);
                    string subscriptionID = reportschedule.CreateSubscription(strReportName, extSettings, strReportDesc, eventType, matchData, parameters);
                    bool createdSubscription = objReportSchedule.CreateReportSubScription(subscriptionID, UserId, strReportName, txtReportName.Value);
                    if (createdSubscription)
                    {
                        string strReport = string.Format("{0} has been scheduleed successfully "Convert.ToString(Request.QueryString["ReportName"]));
                        ApplicationLog.WriteInfo(strReport,"HSW_ReportViewer.btnSaveSchedule_Click", UserId);
                        Response.Write("");
                        rdbtnDailyOptions.Checked = true;
                    }
            }

            catch (SoapException ex)
            {
                ApplicationLog.WriteError(ex.Message,"HSW_ReportViewer.btnSaveSchedule_Click");
            }

User defined Methods to Proceed:
GetMatchData: which we are passing to Reporting Server in Extension Settings .This function will get the start Date/End Date, Daily pattern, weekly pattern, Monthly pattern usingSchedule Definition Class. Schedule Definition will api from Web services Proxy Class.Schedule Definition have variable like StartDateTime, EndDateSpecified, EndDate,Item(Pattern either daily/Weekly/Monthly).
   private string GetMatchData()
        {
            ScheduleDefinition schedule = new ScheduleDefinition();
            schedule.StartDateTime = Convert.ToDateTime(txtStartDate.Value, newCultureInfo("en-US"));
            schedule.EndDateSpecified = true;
            schedule.EndDate = Convert.ToDateTime(txtEndDate.Value, new CultureInfo("en-US"));
            if (rdbtnDailyOptions.Checked)
                schedule.Item = GetDailyPattern();
            else if (rdbtnWeekly.Checked)
                schedule.Item = GetWeeklyPattern();
            else if (rdbtnMonthly.Checked)
            {
                if (rdbtnWeekOfMonthly.Checked)
                    schedule.Item = GetMonthlyDOWRecurrence();
                else
                {
                    schedule.Item = GetMonthlyPattern();
                }
            }

            XmlDocument xmlDoc = GetScheduleAsXml(schedule);
            return xmlDoc.OuterXml;

        }
GetDailyPattern: which return DailyRecurrence. It has Days Interval
        /// Get Daily Pattern
        /// 
        /// 
        private DailyRecurrence GetDailyPattern()
        {

            DailyRecurrence pattern = new DailyRecurrence();
            //if (rdbtnDaily1.Checked)
            pattern.DaysInterval = Convert.ToInt32(txtDay.Value);

            return pattern;
        }
GetWeeklyPattern: which return WeeklyRecurrence. It has Days Of Week, Weeks Interval,WeekIntervalSpeficied

        ///         /// Get Weekly Pattern
        /// 
        /// 
        private WeeklyRecurrence GetWeeklyPattern()
        {
            WeeklyRecurrence pattern = new WeeklyRecurrence();
            DaysOfWeekSelector days = new DaysOfWeekSelector();
            pattern.DaysOfWeek = GetDays(days, rdbtnWeeklist);
            pattern.WeeksIntervalSpecified = true;
            pattern.WeeksInterval = Convert.ToInt32(txtRepeatWeek.Value);
            return pattern;
        }
GetMonthlyPattern: which returns MonthlyRecurrence ,It has Calendar Days as days,month of Year


        /// GetMonthly Pattern
        /// 
        /// 
        private MonthlyRecurrence GetMonthlyPattern()
        {

            MonthlyRecurrence pattern = new MonthlyRecurrence();
            pattern.Days = txtCalendarmonthly.Value;
            pattern.MonthsOfYear = SetMonths();
            return pattern;
        }
GetMonthlyDOWRecurrence:which returns MonthlyDOWRecurrence,It has WhichWeekSpecified, DaysOfWeek, MonthsOfYear, WhichWeek
        /// 
        /// GetMonthlyDOWRecurrence
        /// 
        /// 
        private MonthlyDOWRecurrence GetMonthlyDOWRecurrence()
        {
            MonthlyDOWRecurrence pattern = new MonthlyDOWRecurrence();
            pattern.WhichWeekSpecified = true;
            DaysOfWeekSelector days = new DaysOfWeekSelector();
            pattern.DaysOfWeek = GetDays(days, rdbtnMonthlyWeeks);
            pattern.MonthsOfYear = SetMonths();
            switch (Convert.ToInt32(ddlWeeks.Value))
            {
                case 1:
                    pattern.WhichWeek = WeekNumberEnum.FirstWeek; break;
                case 2:
                    pattern.WhichWeek = WeekNumberEnum.SecondWeek; break;
                case 3:
                    pattern.WhichWeek = WeekNumberEnum.ThirdWeek; break;
                case 4:
                    pattern.WhichWeek = WeekNumberEnum.FourthWeek; break;
                case 5:
                    pattern.WhichWeek = WeekNumberEnum.LastWeek; break;
            }
            return pattern;
        }
GetDays: which returns DaysOfWeekSelector.It has Week Selector.
        /// 

        /// Get Days
        /// 
        /// 
        /// 
        /// 
        private DaysOfWeekSelector GetDays(DaysOfWeekSelector days, RadioButtonListrdbtnWeeklist)
        {
            switch (Convert.ToInt32(rdbtnWeeklist.SelectedValue))
            {
                case 0:
                    days.Sunday = true;
                    break;
                case 1:
                    days.Monday = true;
                    break;
                case 2:
                    days.Tuesday = true;
                    break;
                case 3:
                    days.Wednesday = true;
                    break;
                case 4:
                    days.Thursday = true;
                    break;
                case 5:
                    days.Friday = true;
                    break;
                case 6:
                    days.Saturday = true;
                    break;

            }
            return days;
        }
         /// 

        /// set Months
        /// 
        /// 
        private MonthsOfYearSelector SetMonths()
        {
            MonthsOfYearSelector monthselector = new MonthsOfYearSelector();
            monthselector.January = true;
            monthselector.February = true;
            monthselector.March = true;
            monthselector.April = true;
            monthselector.June = true;
            monthselector.July = true;
            monthselector.August = true;
            monthselector.September = true;
            monthselector.October = true;
            monthselector.November = true;
            monthselector.December = true;
            return monthselector;
        }
    }
GetScheduleAsXml: GetScheduleAsXml will convert the Schedul;e Definition in to Xml Format.

private XmlDocument GetScheduleAsXml(ScheduleDefinition schedule)
        {
            MemoryStream buffer = new MemoryStream();
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(ScheduleDefinition));
            xmlSerializer.Serialize(buffer, schedule);
            buffer.Seek(0, SeekOrigin.Begin);

            XmlDocument doc = new XmlDocument();
            doc.Load(buffer);
            // patch up WhichWeek
            XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
            ns.AddNamespace("rs",
                   "http://schemas.microsoft.com/sqlserver/2003/12/reporting/reportingservices");
            return doc;
        }
GetExtensionSettings: GetExtensionSettings function is used to set the report Delivery Setting these are common to based on Requirement.


      private ExtensionSettings GetExtensionSettings()
        {
            ParameterValue[] extensionParams = new ParameterValue[8];

            ParameterValue ToMail = new ParameterValue();
            ToMail.Name = "TO";
            ToMail.Value = Email;
            extensionParams[0] = ToMail;

            ParameterValue replyTo = new ParameterValue();
            replyTo.Name = "ReplyTo";
            replyTo.Value = string.Empty;
            extensionParams[1] = replyTo;

            ParameterValue includeReport = new ParameterValue();
            includeReport.Name = "IncludeReport";
            includeReport.Value = "false";
            extensionParams[2] = includeReport;

            ParameterValue renderFormat = new ParameterValue();
            renderFormat.Name = "RenderFormat";
            renderFormat.Value = "excel";
            extensionParams[3] = renderFormat;

            ParameterValue priority = new ParameterValue();
            priority.Name = "Priority";
            priority.Value = "NORMAL";
            extensionParams[4] = priority;

            ParameterValue subject = new ParameterValue();
            subject.Name = "Subject";
            subject.Value = txtReportName.Value;
            extensionParams[5] = subject;

            ParameterValue comment = new ParameterValue();
            comment.Name = "Comment";
            comment.Value = strComments;
            extensionParams[6] = comment;

            ParameterValue includeLink = new ParameterValue();
            includeLink.Name = "IncludeLink";
            includeLink.Value = "true";
            extensionParams[7] = includeLink;

            ExtensionSettings extSettings = new ExtensionSettings();
            extSettings.ParameterValues = extensionParams;
            extSettings.Extension = "Report Server Email";

            return extSettings;
        }


ReportServerCredentials: create class called Serializable to pass Network Credentials
[Serializable]
    public sealed class ReportServerCredentials :
        IReportServerCredentials
    {
        string _username = string.Empty;
        string _password = string.Empty;
        string _domain = string.Empty;

        public WindowsIdentity ImpersonationUser
        {
            get
            {
                return null;
            }
        }

        public ICredentials NetworkCredentials
        {
            get
            {
                _username =ConfigurationManager.AppSettings["MyReportViewerUser"].ToString();

                _password =ConfigurationManager.AppSettings["MyReportViewerPassword"].ToString();

                _domain =ConfigurationManager.AppSettings["MyReportViewerDomain"].ToString();

                char[] data = _password.ToCharArray();
                Base64Decoder myDecoder = new Base64Decoder(data);
                StringBuilder sb = new StringBuilder();

                byte[] temp = myDecoder.GetDecoded();
                sb.Append(System.Text.UTF8Encoding.UTF8.GetChars(temp));

                _password = sb.ToString();
                return new NetworkCredential(_username, _password, _domain);
            }
        }

        public bool GetFormsCredentials(out Cookie authCookie,
                    out string userName, out string password,
                    out string authority)
        {
            authCookie = null;
            userName = null;
            password = null;
            authority = null;

            // Not using form credentials
            return false;
        }


    }