Sep 23, 2016

Deferred vs Immediate Query Execution in LINQ


In LINQ, queries have two different behaviors of execution: immediate and deferred. In this article, we will take a quick overview of how Deferred query execution and Immediate Query Execution works in LINQ 

Deferred Query Execution

To understand Deferred Query Execution, let’s take the following example which declares some Employees and then queries all employees with Age > 28:





















OUTPUT: Jack, Rahul
Looking at the query shown above, it appears that the query is executed at the point where the arrow is pointing towards. However that’s not true. The query is actually executed when the query variable isiterated over, not when the query variable is created. This is called deferred execution.
Now how do we prove that the query was not executed when the query variable was created? It’s simple. Just create another Employee instance after the query variable is created
Notice we are creating a new Employee instance after the query variable is created. Now had the query been executed when the query variable is created, the results would be the same as the one we got earlier, i.e. only two employees would meet the criteria of Age > 28. However the output is not the same
OUTPUT: Jack, Rahul, Bill.
What just happened is that the execution of the query was deferred until the query variable was iterated over in a foreach loop. This allows you to execute a query as frequently as you want to, like fetching the latest information from a database that is being updated frequently by other applications. You will always get the latest information from the database in this case.

Immediate Query Execution

You can also force a query to execute immediately, which is useful for caching query results. Let us say we want to display a count of the number of employees that match a criteria.






















In the query shown above, it order to count the elements that match the condition, the query must be executed, and this is done automatically when Count( ) is called. So adding a new employee instanceafter the query variable declaration does not have any effect here, as the query is already executed. The output will be 2, instead of 3.
The basic difference between a Deferred execution vs Immediate execution is that Deferred execution of queries produce a sequence of values, whereas Immediate execution of queries return a singleton value and is executed immediately. Examples are using Count(), Average(), Max() etc.
Note: To force immediate execution of a query that does not produce a singleton value, you can call the ToList(), ToDictionary() or the ToArray() method on a query or query variable. These are called conversion operators which allow you to make a copy/snapshot of the result and access is as many times you want, without the need to re-execute the query.

Apr 18, 2011

Session state -- Cookies

Cut and paste the code as Shown

default.aspx
<%--<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
        <br />
        <br />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>--%>


default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
    {

        //how to check browser supports cookies
        if (Request.Browser.Cookies)
        {
            Response.Write("Browser supports cookies");
        }
        else
        {
            // Web browser not supports cookies
        }


        string MyCookieValue="hello";
        // We need to perform this check first, to avoid null exception
        // if cookie not exists
        if (Request.Cookies["MyCookieName"] != null)
            MyCookieValue = Request.Cookies["MyCookieName"].Value;
        Label1.Text = MyCookieValue;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        // Use this line when you want to save a cookie
        Response.Cookies["MyCookieName"].Value = TextBox1.Text ;
        // How long will cookie exist on client hard disk
        Response.Cookies["MyCookieName"].Expires = DateTime.Now.AddDays(1);

        // To add multiple key/value pairs in single cookie
        Response.Cookies["VisitorData"]["FirstName"] = "Richard";
        Response.Cookies["VisitorData"]["LastVisit"] = DateTime.Now.ToString();

    }
//  HttpCookie MyGreatCookie = new HttpCookie("MyCookieName");
//  MyGreatCookie.Value = "Some cookie value";
//  MyGreatCookie.Expires = DateTime.Now.AddDays(100);
//  Response.Cookies.Add(MyGreatCookie);


//    Cookie size is limited to 4096 bytes. It is not much, so cookies are used to store
//    small amounts of data, often just user id.

//    Also, number of cookies is limited to 20 per website.
//    If you make new cookie when you already have 20 cookies, browser will delete oldest one.

Validation control in Asp.Net 3.5

Remove Comments

default.aspx

<%--<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Validation Server Controls</title>
<script type="text/javascript">
function validatenumber(oSrc,args)
{
        var str = document.getElementById('<%=TextBox5.ClientID%>').value;

        alert(str.length);
        args.IsValid = (args.Value % 6 == 0)
       
}

</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h3>RequiredFieldValidator checks to see that textbox has data before you click submit button.In essence,it enforces Mandatory field rule <br/></h3>
    <h3>When Validation fails, "Required!" will be displayed</h3>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1"  Text="Required!" runat="server" ValidationGroup="Submit" ErrorMessage="Required!" ControlToValidate="TextBox1">
        </asp:RequiredFieldValidator>
        <asp:Button ID="Button1" runat="server" ValidationGroup="Submit" Text="Submit"/>
    </div>
    <div>
    <h3>CompareFieldValidator,as name says, compares two form element's values against each other.It enforces "Same-As" rule.</h3>
        <table>
        <tr>
        <td>
        <asp:Label ID="Label1" runat="server" Text="Enter Password"></asp:Label>
        </td>
        <td>
            <asp:TextBox ID="TextBox2"  TextMode="Password" runat="server"></asp:TextBox>
        </td>
        </tr>
        <tr>
        <td>
        <asp:Label ID="Label2" runat="server" Text="Confirm Password"></asp:Label>
        </td>
        <td>
            <asp:TextBox ID="TextBox3" TextMode="password" runat="server"></asp:TextBox>
        </td>
        <td>
        <asp:Button ID="Button2" runat="server" Text="Login"/>
        </td>
        </tr>
        </table>
        <asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="Passwords don't match!" ControlToValidate="TextBox3"
        ControlToCompare="textbox2" ></asp:CompareValidator>
    </div>
    <div>
    <h3>RangeValidators enforces that values you enter fall under specified range.It enforces "Between-the" rule.</h3>
        <asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="Value must be between 20 and 30" ControlToValidate="RangeTextbox"
        Type="Integer" MinimumValue="20" MaximumValue="30"  Text="*">
        </asp:RangeValidator>
        <asp:TextBox ID="RangeTextbox" runat="server"></asp:TextBox>
        <asp:Button ID="CheckRange" runat="server" Text="CheckRange" />
    </div>
    <div>
    <h3>RegularExpressionValidator checks for a specific pattern.It enforces "As-is" rule.</h3>
        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" Text="*"  ControlToValidate="Textbox4" runat="server"
        ErrorMessage="You must enter an email address" ValidationGroup="CheckMail" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
        <asp:Button ID="Button3" runat="server" ValidationGroup="CheckMail" Text="CheckMail"/>
    </div>
    <div>
    <h3>CustomValidator control to implement custom tailored Validations. It enforces "My-Own" rule.</h3>
        <asp:CustomValidator ID="CustomValidator1" runat="server"
        ControlToValidate="textbox5"  ClientValidationFunction="validatenumber"
        ErrorMessage="Number is not divisible by 6"></asp:CustomValidator>
        <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
        <asp:Button ID="Button4" runat="server" Text="Divisible" />
        </div>
        <asp:ValidationSummary ID="ValidationSummary1" DisplayMode="BulletList"  HeaderText="You received following errors" runat="server" />
    </form>
</body>
</html>
--%>

Dynamic control in asp.net 3.5

default.aspx
<!--
 <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"
            style="height: 26px" />
 </div>
--!>

default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
    {
        TextBox new_textbox = new TextBox();
        new_textbox.ID = "txt" + 1;
        new_textbox.Text = "";
        PlaceHolder1.Controls.Add(new_textbox);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string OptionID = "txt" + 1;
        TextBox tb = (TextBox)PlaceHolder1.FindControl(OptionID);
        Response.Write(tb.Text);
   
    }






Apr 16, 2011

Asp. net 2.0/3.5/4.0 Email code for gmail/hotmail/yahoo-1

default.aspx page

<%--<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
        <br />
        Subject :&nbsp;
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
        <br />
        Email :
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
        <br />
        Msg : &nbsp;&nbsp;
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br />
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Send" /></div>
    </form>
</body>--%>

default.aspx.cs page
public partial class _Default : System.Web.UI.Page
{
    EmailClass email = new EmailClass();
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string file1 = FileUpload1.PostedFile.FileName;
        email.SendMail(TextBox3.Text, TextBox2.Text, TextBox1.Text);
        if (email.a)
        {
            Label1.Text = "Mail Sent !!";
        }
        else
        {
            Label1.Text = "Not Sent";
        }
    }
}

put this class file in app_code folder and save with name :  Email.cs

hello
public class EmailClass
{
    public bool a;
    public EmailClass()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public void SendMail(string msg, string to, string subject)
    {
        //try
        //{
        MailMessage mail = new MailMessage();
        mail.To.Add(to);
        mail.From = new MailAddress("abc@gmail.com");
        mail.Subject = subject;

        string Body = null;
        Body = msg;
        mail.Body = Body;
        mail.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        //smtp.UseDefaultCredentials = false;
        smtp.Host = "smtp.gmail.com";
           smtp.Credentials = new System.Net.NetworkCredential("abc@gmail.com", "password");
        smtp.EnableSsl = true;

        smtp.Send(mail);
        a = true;
        //}
        //catch (Exception ex)
        //{
        //ex.ToString();
        //a = false;
        // }


    }


}






Asp. net 2.0/3.5/4.0 Email code for gmail/hotmail/yahoo

just copy the default.aspx code and remove the comment

default.aspx code

<%--<body>
    <form id="form1" runat="server">
    <div>
    <fieldset style="width: 500px; padding: 10px;">
        <legend>Sending email from GMail</legend>
        <div align="left" style="padding: 5px;">
            Your Gmail EmailID<br />
            <asp:TextBox ID="TextBoxSenderEmailId" runat="server" Width="250px"></asp:TextBox><font color=silver>Please enter your GMailId <br />(e.g yourId@gmail.com)</font><br /><br />
            Friend's EmailId<br />
            <asp:TextBox ID="TextBoxReceiverEmailId" runat="server" Width="250px"></asp:TextBox><font color=silver>Please enter your friend's emailId<br />(e.g abc@xyz.com)</font><br />
            <br />
            Subject<br />
            <asp:TextBox ID="TextBoxSubject" runat="server" Width="350px"></asp:TextBox><br />
            <br />
            Body<br />
            <asp:TextBox ID="TextBoxBody" Width="350px" TextMode="MultiLine" Rows="5" runat="server"></asp:TextBox><br /><br />
            <asp:Button ID="btnSendEmail" runat="server" OnClick="btnSendEmail_Click" Text="Send" />
        </div>
    </fieldset>

    </div>
    </form>
</body>--%>


just copy the sendemail button code and put it in button click event
and make necessary changes

default.aspx.cs

protected void btnSendEmail_Click(object sender, EventArgs e)
    {
        try
        {
            //MailMessage class are used to construct e-mail messages
            MailMessage message = new MailMessage();

            // Collaboration Data Objects (CDO) library allows you to access the Global Address
            // List and other server objects, in addition to the contents of mailboxes
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);

            //basic authentication
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "abc@gmail.com");

            //set your username here
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "password");

            //set your password here
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "True");

            message.From = "xyz@gmail.com";
            message.To = "abc@gmail.com";
            message.Subject = TextBoxSubject.Text ;
            message.Body = TextBoxBody.Text ;

            //if (!txtAttach.Text.Equals("")) //adding attachments.
            //{
            //    MailAttachment attach = new MailAttachment(txtAttach.Text);
            //    if (attach != null)
            //    {
            //        message.Attachments.Add(attach);
            //    }
            //}
            SmtpMail.SmtpServer = "smtp.gmail.com";
           
            //The real server goes here
            SmtpMail.Send(message);

            Response.Write("Your message has been sent.");
            //MessageBox.Show("Your message has been sent.", "Mail Sent",MessageBoxButtons.OK, MessageBoxIcon.None);
        }
        catch (Exception ex)
        {
            //MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    //I have to attach a file so,I created a button called btnAttach.
    private void btnAttach_Click_1(object sender, EventArgs e)
    {
        //DialogResult clicked = OpenattachDialog.ShowDialog();
        //if (clicked.Equals(DialogResult.OK))
        //{
        //    txtAttach.Text = OpenattachDialog.FileName;
        //}
    }//btnAttach






Image Gallery - Image Add/Delete/Preview - Single Page App -

https://github.com/TheKalin/jQuery-File-Upload.MVC5 Helper Class / Models   public class FilesHelperDB     {         dbImageGallery...