Wednesday 30 November 2016

.asp xml service



presentation layer -> service -> server data


add .ado (model1.edmx) to entityframe data library


add webservice1.asmx to service .asp project
service project creates service
//~/service/webservice.asmx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using entityframe;

namespace service
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public dto[] get_instructors()
        {
            var db = new CTTIEntities();

            var instructors = db.Instructors.
                Select(x => new dto
                {
                    Id = x.Id,
                    FirstName = x.FirstName,
                    LastName = x.LastName
                }).ToArray();

            return instructors;
        }

        [WebMethod]
        public void add(dto new_instructor)
        {
            var db = new CTTIEntities();

            var i = new Instructor();
            i.FirstName = new_instructor.FirstName;
            i.LastName = new_instructor.LastName;

            db.Instructors.Add(i);
            db.SaveChanges();
        }
    }
}

--------------------------------------------------------

copy connection string from ~/entityframe/app.config

 <connectionStrings>
  <add name="CTTIEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=localhost;initial catalog=CTTI;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

into

~/presentation/web.config
and ~/service/web.config



right click service project, select property
select webservice1.asmx as start page


right click on service project, set as start up project



run solution, see get_instructors method from webservice1.asmx


click invoke


get_instructors method returns instructor info
test is successful


//dto.cs (data transfer object) to service project

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace service
{
    public class dto
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

//copy property from instructor.cs in entityframe (data) project


add service to presentation project
presentation consume service


click advanced


click add web reference


click web service in this solution


select webservice1


if new webmethod is added in ~/service/webservice1.asmx, right click -> update




~/presentation/default.aspx



objectdata source, select ~/presentation/xml_service/webservice1.asmx
data source from web reference get_instructor() method


select get_instructor method
service consumed



set presentation as start project
set data gridview source to objectdatasource


//~/presentation/default.aspx.cs

using object_form1.xml_service; //use service reference
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace object_form1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            var ins = new dto();
            ins.FirstName = TextBox1.Text;
            ins.LastName = TextBox2.Text;

            var proxy = new xml_service.WebService1(); //select service
            proxy.add(ins); //method from service
            Page.DataBind(); //update table/ data pull back from server
        }
    }
}




Friday 25 November 2016

.asp authentication menu dropdown




//login.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ctti.Data;
using System.Web.Security;

namespace CttiDemo
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void uxAuthenticate_Click(object sender, EventArgs e)
        {
            //authenticate the user against the database
            var db = new CTTIEntities1();
            var auth = db.Authentications.SingleOrDefault(a => a.Username == uxUserId.Text
                                                          && a.Password == uxPassword.Text);
            if(auth != null)
            {
                var student = string.Format("{0} {1}", auth.Student.FirstName,
                                                       auth.Student.LastName);
                //Redirect using the FormsAuthentication class
                FormsAuthentication.RedirectFromLoginPage(student, false);
            }
        }
    }
}

-----------------------------------------------------------------



//~/students/web.config

<?xml version="1.0"?>
<configuration>
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>
</configuration>

----------------------------------------------------------------------

//~/web.config
//add <authentication> under <system.web>

<system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Login.aspx" />
    </authentication>
    <compilation debug="true" targetFramework="4.6.1">
      <assemblies>
        <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
        <add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.6.1" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
        
      </controls>
    </pages>
  </system.web>

----------------------------------------------------------------------------

//site.master.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CttiDemo
{
    public partial class SiteMaster : MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.User.Identity.IsAuthenticated)
            {
                uxWelcome.Text = "Welcome " + Page.User.Identity.Name;
                uxLogin.Text = "Logout";
                uxLogin.NavigateUrl = "~/Default.aspx";
            }
            else
            {
                uxWelcome.Text = string.Empty;
                uxLogin.Text = "LogIn";
                uxLogin.NavigateUrl = "~/Login.aspx";
            }
        }
    }
}

-----------------------------------------------------------------------

//site.master.aspx


<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="CttiDemo.SiteMaster" %>

<!DOCTYPE html>

<html lang="en">
<head runat="server">
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title><%: Page.Title %> - My ASP.NET Application</title>

    <asp:PlaceHolder runat="server">
        <%: Scripts.Render("~/bundles/modernizr") %>
    </asp:PlaceHolder>

    <webopt:bundlereference runat="server" path="~/Content/css" />
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />

</head>
<body>
    <form runat="server">
        <asp:ScriptManager runat="server">
            <Scripts>
                <%--To learn more about bundling scripts in ScriptManager see http://go.microsoft.com/fwlink/?LinkID=301884 --%>
                <%--Framework Scripts--%>
                <asp:ScriptReference Name="MsAjaxBundle" />
                <asp:ScriptReference Name="jquery" />
                <asp:ScriptReference Name="bootstrap" />
                <asp:ScriptReference Name="respond" />
                <asp:ScriptReference Name="WebForms.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebForms.js" />
                <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" />
                <asp:ScriptReference Name="MenuStandards.js" Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" />
                <asp:ScriptReference Name="GridView.js" Assembly="System.Web" Path="~/Scripts/WebForms/GridView.js" />
                <asp:ScriptReference Name="DetailsView.js" Assembly="System.Web" Path="~/Scripts/WebForms/DetailsView.js" />
                <asp:ScriptReference Name="TreeView.js" Assembly="System.Web" Path="~/Scripts/WebForms/TreeView.js" />
                <asp:ScriptReference Name="WebParts.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebParts.js" />
                <asp:ScriptReference Name="Focus.js" Assembly="System.Web" Path="~/Scripts/WebForms/Focus.js" />
                <asp:ScriptReference Name="WebFormsBundle" />
                <%--Site Scripts--%>
            </Scripts>
        </asp:ScriptManager>

        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" runat="server" href="~/">
                        <img runat="server" src="~/Images/ctti_banner.jpg" style="width:300px" />
                    </a>
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li><a runat="server" href="~/">Home</a></li>
                        <li><a runat="server" href="~/About">About</a></li>
                        <li><a runat="server" href="~/Contact">Contact</a></li>
                        <li><a runat="server" href="~/Instructors">Instructors</a></li>
                        <li><a runat="server" href="~/Courses">Courses</a></li>
                        <li><a runat="server" href="~/Admin">Admin</a></li>                        
                        <li class="dropdown">
                            <a runat="server" href="#" data-toggle="dropdown" class="dropdown-toggle">
                                Students<b class="caret"></b>
                            </a>
                            <ul class="dropdown-menu">
                                <li><a runat="server" href="~/Students/Enrollment">Enrollment</a></li>
                                <li><a runat="server" href="~/Students/Payment">Payment</a></li>
                            </ul>
                        </li>
                    </ul>
                </div>
                <div>
                    <asp:Label ID="uxWelcome" runat="server" ForeColor="White"></asp:Label>
                    &nbsp;&nbsp;<asp:HyperLink ID="uxLogin" runat="server"></asp:HyperLink>
                </div>
            </div>
        </div>
        <div class="container body-content">
            <div class="row">
                <div class="col-md-1">
                    &nbsp;
                </div>
                <div class="col-md-10" style="height:300px">
                    <asp:ContentPlaceHolder ID="MainContent" runat="server">
                    </asp:ContentPlaceHolder>             
                </div>
                <div class="col-md-1">
                    &nbsp;            
                </div>
            </div>            
            <hr />
            <footer>
                <p>&copy; <%: DateTime.Now.Year %> - My ASP.NET Application</p>
            </footer>
        </div>

    </form>
</body>
</html>

-----------------------------------------------------------------------
//logout
//site.master.cs

protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.User.Identity.IsAuthenticated)
            {
                uxWelcome.Text = "Welcome " + Page.User.Identity.Name;
                uxLogin.Text = "Logout";              
            }
            else
            {
                uxWelcome.Text = string.Empty;
                uxLogin.Text = "LogIn";
                uxLogin.PostBackUrl = "~/Login.aspx";
            }
        }

        //linked button
        protected void uxLogin_Click(object sender, EventArgs e)
        {
            if (Page.User.Identity.IsAuthenticated)
            {
                //remove the authentication
                uxWelcome.Text = string.Empty;
                uxLogin.Text = "LogIn";
                uxLogin.PostBackUrl = "~/Login.aspx";
                FormsAuthentication.SignOut();
                Session.Clear();
                Session.Abandon();
                Response.Redirect("~/Default.aspx");
            }
        }

Wednesday 23 November 2016

在印度疯传的视频,目前最红的MV



https://www.youtube.com/watch?v=sc3knqv2bcU

這個女生好厲害! 她的道具都藏在那裡?


https://www.youtube.com/watch?v=oDLkMXTUVwA

比四川變臉 還更特別的表演













Welcome To The “Melt Up”

The good news, as shown in the next chart, is the market was able to clear that downtrend resistance this week and turn the previous “sell signal” back up. As suggested previously, it is not surprising the markets are pushing all-time highs as we saw on Friday.
S&P 500
S&P 500
But what happened next?
Importantly, with next week being a light trading week, it would not be surprising to see markets drift higher.
However, expect a decline during the first couple of weeks of December as mutual funds and hedge funds deal with distributions and redemptions. That draw down, as seen in early last December, ran right into the Fed rate hike that set up the sharp January decline.
As I have noted above, there are many similarities in market action between the “post-Trexit” bounce, “Brexit” and last December’s Fed rate hike. I have highlighted there specific areas of note in the chart above.
As with ‘Brexit’ this past June, the markets sold off heading into the vote assuming a vote to leave the Eurozone would be a catastrophe. However, as the vote became clear that Britain was voting to leave, global Central Banks leaped into action to push liquidity into the markets to remove the risk of a market meltdown. The same setup was seen as markets plunged on election night and once again liquidity was pushed into the markets to support asset prices forcing a short-squeeze higher.
So, with that breakout, I am increasing equity risk exposure to portfolios.
However, I am doing so with an offsetting hedge by adding exposure to interest rate sensitive sectors and beaten down opportunities. The reason for those hedges is due to the combined current backdrop of a sharply higher dollar and interest rates, which have historically been the ingredients for rather nasty corrections.
The chart below is the 60-day moving average of total 60-day change of both interest rates and the dollar. In other words, I have used a 60-day moving average to smooth out the volatility of the 60-day net change in the dollar and rates so a clearer trend could be revealed. I have then overlaid that moving average with the S&P 500 index.
USD And Interest Rates
USD And Interest Rates
Not surprisingly, since stronger rates negatively impacts economic growth due to increased borrowing costs, and a stronger dollar reduces exports and ultimately corporate earnings, markets tend not to like the combination of two very much.
My analysis agrees with Dr. Lacy Hunt via Hoisington Investment Management who recently stated:
The recent rise in market interest rates will place downward pressure on the velocity of money (V) and also the rate of growth in the money supply (M). This is not a powerful effect, but it is a negative one. Some additional saving or less spending will occur, thus giving V a push downward. So, in effect, the markets have tightened monetary conditions without the Fed acting. If the Fed raises rates in December, this will place some additional downward pressure on both M and V, and hence on nominal GDP. Thus, the markets have reduced the timeliness and potential success of the coming tax reductions.
Another negative initial condition is that the dollar has risen this year, currently trading close to the 13-year high. The highly relevant Chinese yuan has slumped to a seven-year low. These events will force disinflationary, if not deflationary forces into the US economy. Corporate profits, which had already fallen back to 2011 levels, will be reduced due to several considerations. Pricing power will be reduced, domestic and international market share will be lost and profits of overseas subs will be reduced by currency conversion. Corporate profits on overseas operations will be reduced, but with demand weak and current profits under downward pressure, the repatriated earnings are likely to go into financial rather than physical investment.
Markets have a pronounced tendency to rush to judgment when policy changes occur. When the Obama stimulus of 2009 was announced, the presumption was that it would lead to an inflationary boom. Similarly, the unveiling of QE1 raised expectations of a runaway inflation. Yet, neither happened. The economics are not different now.Under present conditions, it is our judgment that thedeclining secular trend in Treasury bond yields remains intact.
While not all combined increases led to major market events/crisis as noted above, more often than not equity participants tended not to fare exceptionally well.
That’s just reality.

Welcome To The “Melt-Up”

However, while economic and fundamental realities HAVE NOT changed since the election, markets are pricing in expected impacts of changes to fiscal policy expecting a massive boost to earnings from tax rate reductions and repatriated offshore cash to be used directly for stock buybacks.
To wit:
We expect tax reform legislation under the Trump administration will encourage firms to repatriate $200 billion of overseas cash next year. A significant portion of returning funds will be directed to buybacks based on the pattern of the tax holiday in 2004. – Goldman Sachs (NYSE:GS)
Repatriated-Fund Outlook
Repatriated-Fund Outlook
But it is not just the repatriation but lower tax rates that will miraculously boost bottom-line earnings. This time from Deutsche Bank (DE:DBKGn):
Every 5pt cut in the US corporate tax rate from 35% boosts S&P EPS by $5. Assuming that the US adopts a new corporate tax rate between 20-30%, we expect S&P EPS of $130-140 in 2017 and $140-150 in 2018. We raise our 2017E S&P EPS to $130.
See…buy stocks. Right?
Maybe not so fast. Here is the problem.
While you may boost bottom line earnings from tax cuts, the top line revenue cuts caused by higher interest rates, inflationary pressures, and a stronger dollar will exceed the benefits companies receive at the bottom line.
I am not discounting the rush by companies to buy back shares at the greatest clip in the last 20-years to offset the impact to earnings by the reduction in revenues. However, none of the actions above go to solving the two things currently plaguing the economy – real jobs and real wages.
The rush by Wall Street to price in fiscal policy, which may or may not arrive in a timely manner, will likely push the markets higher in the short-term completing the final leg of the current bull market cycle. This was a point I addressed back in October on the potential for a rise to 2400 in the markets. With the breakout of the market to new highs, the bullish spirits have emboldened investors to rush into the most speculative areas of the market.
For now, it is all about the “Trump” trade. Which is interesting considering that just before the election we were all told how horrible a Trump election would be for the world economy.
However, it should be noted that despite the “hope” of fiscal support for the markets, longer-term “sell signals” only witnessed during major market-topping processes currently remain as shown below.
S&P 500 Sell Signals
S&P 500 Sell Signals
The problem for the new Administration is the economy is already pushing in excess of 100% of debt-to-GDP which by its very nature reduces the impact of stimulative programs such as infrastructure spending. But the debt itself is also a problem and a point made today by Fed vice chair Fischer issued a clear warning as to the “enormous uncertainty around new US fiscal policies.”
  • FISCHER: NOT A LOT OF ROOM TO INCREASE U.S. DEFICIT WITHOUT ADVERSE CONSEQUENCES DOWN THE ROAD
But that is a story for another day.
For now, the market is ignoring such realities in the “hope”this time is different. The market has regained its running bullish trend line for now which keeps the “bulls” in charge.
As shown below, the breakout to new highs does clear the markets for a further advance. However, while the technicals suggest a move to 2400, it is quite possible it could be much less. Notice in the bottom section of the chart below. Turning the current “sell signal” back into a “buy signal” at such a high level does not give the markets a tremendous amount of runway.
S&P 500 Technicals
S&P 500 Technicals
Furthermore, the market is also pushing into resistance of the previously supportive bullish trend lines. This may limit the upside advance temporarily as the markets work off the currently extreme overbought conditions following the advance from the election lows.
S&P 500 Pushing Into Resistance
S&P 500 Pushing Into Resistance
There is also the issue of deviations above the long-term trend line. Trend lines and moving averages are like “gravity.” Prices can only deviate so far from their underlying trends before eventually “reverting to the mean.” However, as we saw in 2013-14, given enough liquidity prices can remain deviated far longer than would normally be expected. (I have extrapolated move to 2400 using weekly price data from the S&P 500.)
A move to 2400 would once again stretch the limits of deviation from the long-term trend line likely leading to a rather nasty reversion shortly thereafter.
S&P 500 Trend Support
S&P 500 Trend Support
We can see the deviation a little more clearly in the analysis below. Once again, the data in the orange box is an extrapolated price advance using historical market data. The dashed black line is the 6-month moving average (because #BlackLinesMatter) and the bar chart is the deviation of the markets from price average.
Historically speaking deviations of such an extreme rarely last long. As discussed above, while it is conceivable that a breakout of the current consolidation pattern could lead to a sharp price advance, it would likely be the last stage of the bull market advance before the next sizable correction.
S&P 500 Deviation
S&P 500 Deviation

This Won’t End Well

As shown in the first chart above, the rising in the dollar and interest rates will lead to an explosion somewhere in the economy and the markets that will negate a good chunk, if not all, of any fiscal policy measures implemented by the next administration.
Where, and when, are the two questions that cannot be answered.
How big of a correction could be witnessed? The chart below, once again extrapolated to 2400, shows the mathematical retracement levels based on the Fibonacci sequence. The most likely correction would be back to 2000-ish which would officially enter “bear market” territory of 23.6%. However, most corrections, historically speaking, generally approach the 38.2% correction level. Such a correction would be consistent with a normal recessionary decline and bear market.
S&P 500 Retracement Levels
S&P 500 Retracement Levels
Of course, given the length and duration of the current bull-market with extremely weak fundamental underpinnings, leverage, and over-valuations, a 50% correction back towards the 1300 level is certainly NOT out of the question. Let’s not even discuss what would happen if go beyond that, but suffice it to say it wouldn’t be good.
And when it does, the media will ask first “why no saw it coming.” Then they will ask “why YOU didn’t see it coming when it so obvious.”
In the end, being right or wrong has no effect on the media as they are not managing money nor or they held responsible for consistently poor advice. However, being right or wrong has a very big effect on you.
Yes, a move to 2400 is viable, but there must be a sharp improvement in the underlying fundamental and economic backdrop. Right now, there is little evidence of that in the making, and with the rise of the dollar and rates, the Fed tightening monetary policy and real consumption weak there are many headwinds to conquer. Regardless, it will likely be a one-way trip and it should be realized that such a move would be consistent with the final stages of a market melt-up.
As Wile E. Coyote always discovers as he careens off the edge of the cliff, “gravity is a bitch.”