December 16, 2016

Javascript vs Jquery


  • jQuery in itself is written in JavaScript.
  • JavaScript was first appeared on 1995 while jQuery was initially released in August 26, 2006.
  • JavaScript is an Object Oriented Programming (OOP) language while jQuery is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML.
  • JavaScript is a scripting language that works with all web browsers while jQuery is only a framework that is a fast and concise JavaScript library that simplifies the HTML document.
  • In case of using JavaScript you are required to writer your own script that can be time consuming. In case of using jQuery you are not required to write much scripting that already exists in libraries.
  • JavaScript is combination of both ECMA script and DOM while jQuery has DOM.
  • JavaScript has many processes in creating web-based applications while creating a web-based application with the help of jQuery has become easier.
  • Animations are not possible using JavaScript while these can be easily created using jQuery
  • jQuery support only Firefox, Google Chrome, Safari, Opera, and Internet Explorer while JavaScript is supported by all major web browsers without plug-ins.
javascript Jquery
function changeBackground(color) {
   document.body.style.background = color;
}
onload="changeBackground('red');"
$('body').css('background', '#ccc'); 
document.getElementById("example") $('#example')
document.getElementsByClassName("example") $('.example')
document.getElementById("btn")
.addEventListener("click", function () {
    document.getElementById("txtbox").value = "Hello World";
});
$('#btn').click(function () {
    $('#txtbox').val('Hello World');
});

datetime code


Dim dateString, format As String
dateString = "MM" & "/" & dd & "/" & yyyy & " " & HH & ":00"
dateString = dateString.Replace("-", "/")

Dim provider As CultureInfo = CultureInfo.InvariantCulture
format = "MM/dd/yyyy HH:mm:ss"
Try
   fromdate = Date.ParseExact(dateString, format, provider)
Catch ex As FormatException
   ShowAlert(ex.Message)
End Try

Generate Captcha in asp.net



Page : GenerateCaptcha.aspx

        protected void Page_Load(object sender, EventArgs e)
        {
            ClsWorkFlow objwork = new ClsWorkFlow();
            string strCaptcha = objwork.Decrypt(Request.QueryString["cap"]);

            Response.Clear();
            int height = 30;
            int width = 100;

            Bitmap bmp = new Bitmap(width, height);
            RectangleF rectf = new RectangleF(10, 5, 0, 0);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            Font f = new Font("Thaoma", 12, FontStyle.Italic);
            g.DrawString(strCaptcha, f, Brushes.Red, rectf);
            g.DrawRectangle(new Pen(Color.Red), 1, 1, width - 2, height - 2);
            g.Flush();
            Response.ContentType = "image/jpeg";
            bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
            g.Dispose();
            bmp.Dispose();
        }

Call the page 

        public void FillCapctha()
        {
            try
            {
                Random random = new Random();
                string combination = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
                StringBuilder captcha = new StringBuilder();
                for (int i = 0; i <= 6; i++)
                {
                    captcha.Append(combination[random.Next(combination.Length)]);
                }
                ViewState["captcha"] = captcha.ToString();
                helper obj = new helper();
                ClsWorkFlow objwork = new ClsWorkFlow();
                imgCaptcha.ImageUrl = "GenerateCaptcha.aspx?cap=" + ViewState["captcha"].ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

November 25, 2016

Javascript validation and useful methods

Perfect Calendar in textbox with some validation


<asp:TextBox ID="txtFromDate" CssClass="Textbox" runat="server" ValidationGroup="Report"
Width="120px" onkeyup="if(this.value != ''){this.value = '';confirm('Please select from calendar.');}return false;"></asp:TextBox>

 <asp:RequiredFieldValidator ID="rfvtxtFromDate" runat="server" ErrorMessage="Enter From Date"
                        ControlToValidate="txtFromDate" ValidationGroup="Report">*</asp:RequiredFieldValidator>

<cc1:CalendarExtender ID="ceFromDate" runat="server" TargetControlID="txtFromDate"
Format="dd/MM/yyyy"></cc1:CalendarExtender>

On Key Up event


function validateAplabeticValue(that) {
            var re = /[^a-z.\s]/gi;

            if (re.test(that.value)) {
                that.value = that.value.replace(re, '');
                alert('Enter only alphabetic value');
            }
        }

  <asp:TextBox ID="txtExtstakhld" runat="server" 
onkeyup="validateAplabeticValue(this);"
MaxLength="30" Width="300px"></asp:TextBox>

Check javascript enable or not


 <noscript>
        <div>
            You must enable javascript to continue.
        </div>
    </noscript>

if you are using old browser then run the below script
 <!--[if lt ie 9]>
<script type="text/javascript">
alert("You are using old IE version, Please upgrade to the latest");
         window.location="http://windows.microsoft.com/en-IN/internet-explorer/download-ie";
</script>
<![endif]-->


Allow Only Alphabets


var specialKeys = new Array();
specialKeys.push(0); //Tab for Firefox
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(32); //Space
function onlyAlphabets(e, t) {
    try {
        if (window.event) {
            var charCode = window.event.keyCode;
        }
        else if (e) {
            var charCode = e.which;
        }
        else { return true; }
        if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
            return true;
        else {

            for (var num in specialKeys) {
                if (charCode == specialKeys[num])
                    return true;
            }
            return false;
        }
    }
    catch (err) {
        alert(err.Description);
    }
}


Allow Only Alphabets


function onlyAlphabetsNoSpace(e, t) {
    try {
        if (window.event) {
            var charCode = window.event.keyCode;
        }
        else if (e) {
            var charCode = e.which;
        }
        else { return true; }
        if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
            return true;
        else {
            for (var num in specialKeys) {
                if (specialKeys[num] == 32)
                    return false;
                if (charCode == specialKeys[num])
                    return true;
            }
            return false;
        }
    }
    catch (err) {
        alert(err.Description);
    }
}


<asp:TextBox runat="server" ID="txtidfirstname" MaxLength="12" CssClass="txt-box-full" 
onkeypress="return onlyAlphabetsNoSpace(event,this);" ondrop="return false;" onpaste="return false;" />


 function validateAplabeticValue(that) {
            var re = /[^a-z.\s]/gi;

            if (re.test(that.value)) {
                that.value = that.value.replace(re, '');
                alert('Enter only alphabetic value');
            }
        }

Allow alphanumeric


function IsAlphaNumeric(e) {

    var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
    var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
    if (ret) {
        return true;
    } else {
        for (var num in specialKeys) {
            if (keyCode == specialKeys[num])
                return true;
        }
        return false;
    }
}


Allow Decimal Number


function isNumberDecimalKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    } else {
        // If the number field already has . then don't allow to enter . again.
        if (evt.target.value.search(/\./) > -1 && charCode == 46) {
            return false;
        }
        return true;
    }
}


Allow Number


function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    //if (charCode > 31 && (charCode < 48 || charCode > 57)) {
       
    //    return false;
    //}
    //return true;
    if (charCode > 47 && charCode < 58) {
        return true;
    } else {
        for (var num in specialKeys) {
            if (charCode == specialKeys[num])
                return true;
        }
        return false;
    }
}

Change the Value of other control


    function ddlPan() {
        var ddl = document.getElementById("<%=ddlPAN.ClientID%>");
        var SelVal = ddl.options[ddl.selectedIndex].value;
        if (SelVal == "N" || SelVal == "") {
            document.getElementById("<%=txtPANNumber.ClientID%>").value = "";
            document.getElementById("<%=txtPANNumber.ClientID%>").disabled = true;
        }
        else
            document.getElementById("<%=txtPANNumber.ClientID%>").disabled = false;
    }


    <asp:DropDownList runat="server" ID="ddlPAN" CssClass="dropdown-box-full" onchange="ddlPan()">

November 8, 2016

Common model popup for all the pages

we can use common model popup for all pages

Master Page Code snippet

 <cc1:ModalPopupExtender ID="mppopup" runat="server" BehaviorID="modalpopup" BackgroundCssClass="backgroundmodal"
            TargetControlID="btnpopup" CancelControlID="btnCancel" OkControlID="btnOkay"
            PopupControlID="panelmodal">
        </cc1:ModalPopupExtender>
        <asp:Button runat="server" ID="btnpopup" OnClick="btnpopup_Click" Text="PopUp" CssClass="hide" /><!--dummy button-->
        <asp:Panel ID="panelmodal" Style="display: none" CssClass="modal-dialog" runat="server">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" runat="server" id="myModalheader">Alert</h4>
                </div>
                <div class="modal-body">
                    <div class="alert-content">
                        <p runat="server" id="palertmessage">Hello, this is an alert</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <asp:Button ID="btnOkay" runat="server" Text="Ok" CssClass="btn-small" UseSubmitBehavior="true" OnClientClick="javascript:skipLN();" />
                    <asp:Button ID="btnCancel" runat="server" Text="Can" CssClass="btn-small" UseSubmitBehavior="true" OnClientClick="javascript:skipLN();" />
                </div>
            </div>
        </asp:Panel>


class - find the control from master page and did the dynamic activity

public void CallModalPopup(MasterPage master, string RedirectPageName, string AlertBody, string AlertHeader = "Notification", string OKtext = "OK", string CanText = "CANCEL", bool ShowOk = true, bool showCancel = true, bool skipLN = true)
        {

            AjaxControlToolkit.ModalPopupExtender mp = (AjaxControlToolkit.ModalPopupExtender)master.FindControl("mppopup");

            System.Web.UI.HtmlControls.HtmlGenericControl body = (System.Web.UI.HtmlControls.HtmlGenericControl)master.FindControl("palertmessage");

            System.Web.UI.HtmlControls.HtmlGenericControl header = (System.Web.UI.HtmlControls.HtmlGenericControl)master.FindControl("myModalheader");

            Button okay = (Button)master.FindControl("panelmodal").FindControl("btnOkay");
            Button cancel = (Button)master.FindControl("panelmodal").FindControl("btnCancel");

            okay.OnClientClick = "";
            if (RedirectPageName != "")
                if (RedirectPageName.Contains("window.open"))
                    okay.OnClientClick = RedirectPageName;
                else if (skipLN)
                    okay.OnClientClick = "javascript:skipLN();window.location.href='" + RedirectPageName + "'";
                else
                {
                    okay.OnClientClick = "window.location.href='" + RedirectPageName + "'";
                    HttpContext.Current.Session["UserID"] = "ERROR";
                }
            okay.UseSubmitBehavior = true;
            okay.Text = OKtext;
            okay.Focus();
            cancel.Text = CanText;
   
            if (!showCancel)
                cancel.Attributes.Add("style", "display:none !important;");
            body.InnerText = AlertBody;
            header.InnerText = AlertHeader;

            mp.Show();
   
        }

call from Page

CallModalPopup(this.Master, "", "You can register interest for upto 3 interest areas and job roles", showCancel: false);

November 6, 2016

WWF -Project structure

PROJECT STRUCTURE CHANGED AS FRAMEWORK CHANGED







Part 1: Windows workflow foundation (WWF)

WWF is workflow Framework for Microsoft product.

WF Framework is compose of library,Execution Engine, Rules engine, a number of activities, a number of supporting runtime services.

WF contains graphical debugger.

The engine is designed in such a way that the developer has a free choice between building the workflow as code constructs or in a declarative fashion using XAML. 

Workflow: A workflow models a process as a set of activities applied to work in progress.

A workflow is constructed from a number of activities, and these activities are executed at runtime.

A number of built-in activities can be used for general-purpose work, 
and you can also create your own custom activities and plug these into the workflow as necessary


Workflow Runtime Engine: 
Every running workflow instance is created and maintained by an in-process runtime engine that is commonly referred to as the workflow runtime engine. 

There can be several workflow runtime engines within an application domain. 

Each instance of the runtime engine can support multiple workflow instances running concurrently.

Because a workflow is hosted in-process, a workflow can easily communicate with its host application.


Why should we use ?

  • Can see workflow visually. (More understandable way)
  • Separation between business logic and its implementation
  • No Need to Complie the workflow as it is xml. This flexibility even goes further and the engine allows for the runtime alteration of the executing workflow.
  • Due to it is library,it is flexible to included in application or site.

Activities : Activities run like tree structure.
Activities have two types of behavior
Runtime: specifies the actions upon execution.
Designtime: controls the appearance of the activity and its interaction while being displayed within the designer. 

Services
The workflow runtime engine uses many services when a workflow instance runs. Windows Workflow Foundation provides default implementations of the runtime services that meet the needs of many types of applications, such as a persistence service, which stores the execution details of a workflow instance in a SQL database. These service components are pluggable, which allows applications to provide these services in ways that are unique to their execution environment. Other types of services used by the runtime engine include scheduling services, transaction services, and tracking services.

Custom services can be created to extend the Windows Workflow Foundation platform by deriving from the base service classes. An example of this would be a persistence service that uses an XML file instead of a database for storage.

Persistency :

Windows Workflow Foundation simplifies the process of creating stateful, long-running, persistent workflow applications. The workflow runtime engine manages workflow execution and enables workflows to remain active for long periods of time and survive application restarts. This durability is a key tenet of Windows Workflow Foundation. It means that workflows can be unloaded from memory while awaiting input and serialized into a persistent store, such as a SQL database or XML file. Whenever the input is received, the workflow runtime engine loads the workflow state information back into memory and continues execution of the workflow.

Windows Workflow Foundation provides the SqlWorkflowPersistenceService that integrates well with Microsoft SQL Server to persist workflow information easily and efficiently. You can also create your own persistence service to store workflow state information anywhere you want by deriving from the WorkflowPersistenceService base class. 

Tracking
Tracking is the ability to specify and capture information about workflow instances and store that information as the instances execute. Windows Workflow Foundation provides the SqlTrackingService, which is a tracking service that uses a SQL database to store the collected tracking information. You can also write your own tracking service to collect and store this information in any format that your application requires.

When a new workflow is created, the tracking service requests a tracking channel to be associated with that workflow. All of the tracking information from the workflow is then sent to this tracking channel.

The tracking service can track three types of events:
  • Workflow instance events
  • Activity events
  • User events
You can configure the type and amount of information that your service wants to receive for a particular workflow instance or types of workflow by providing a tracking profile.

The tracking framework also provides the ability to extract information about activities or the workflow during an event. If a specific property or field in your activity or workflow needs to be tracked, you can provide this information in the extracts section of the tracking profile, and that information will be extracted during the specified event. 

Serialization
Workflows, activities, and rules can be serialized and deserialized. This enables you to persist them, use them in workflow markup files, and view their properties, fields, and events in a workflow designer.

Windows Workflow Foundation provides default serialization capabilities for standard activities, or you can create your own for custom activities. For example, with a custom activity serializer, you can decide which members are serialized and how they are serialized. This determines if those members are visible or hidden in a workflow designer

October 31, 2016

Dynamic Data site in ASP.NET


If you want to do only CRUD operation on site then this is the best template
Dynamic Data supports scaffolding, which is a way to automatically generate Web pages for each table in the database. Scaffolding lets you create a functional Web site for viewing and editing data based on the schema of the data. You can easily customize scaffolding elements or create new ones to override the default behavior.


https://msdn.microsoft.com/en-us/library/ee845452.aspx

http://www.c-sharpcorner.com/UploadFile/Dorababu742/dynamic-data-entities-web-application/

http://www.dotnetcurry.com/ShowArticle.aspx?ID=232

October 1, 2016

LINQ

string[] words = { "hello", "wonderful", "linq", "beautiful", "world" };
or
string[] words = new string[] { "hello", "wonderful", "linq","beautiful", "world" };

var shortWords =
from word in words
where word.Length <= 5
select word;

foreach (var item in shortWords)
Console.WriteLine(item);

var s = words.Where(c => c.Length <= 5);

foreach (var item in s)
Console.WriteLine(item);
------------------------------------------------------

UnType Array


Object[] array = { "String", 12, true, 'a' };
foreach (var item in array)
 Console.WriteLine(item);

var types = array.Select(item => item).Select(item => item.GetType().Name);
foreach (var item in types)
Console.WriteLine(item);
------------------------------------------------------

Multiple Object and LINQ -Filtering, sorting,comparing

    class Book
    {
        public string Title { get; set; }
    }

List<Book> books = new List<Book>()
            {
                                                  new Book { Title="LINQ in Action" },
                                                  new Book { Title="LINQ for Fun" },
                                                  new Book { Title="Extreme LINQ" }
            };

or

    Book[] books = {
                        new Book { Title="LINQ in Action" },
                        new Book { Title="Action for Fun" },
                        new Book { Title="Extreme LINQ" }
                    };


    var titles = books.Where(book => book.Title.Contains("Action")).Select(book => book.Title);

 foreach (var item in titles)
 Console.WriteLine(item);

Single object -check length,contain any string or find self attribute value

Book b = new Book();
b.Title = "pravin patil";


var s = b.Title.Length.Equals(("pravin patil").Length);

Console.WriteLine(s);


LINQ to XML

string usersName = "pravin";
XElement name = new XElement("name", usersName);
Console.WriteLine(name);

Output


<name>pravin</name>
------------------------------------------------------
void Main()
{
  XElement name = new XElement("method", GetUsersName());
  Console.WriteLine(name);
}
private string GetUsersName() { return "method content can keep in xml"; }

Output
<method>method content can keep in xml</method>
------------------------------------------------------
XElement x= new XElement("book", new XAttribute("pubDate", "July 31, 2006"));
Console.WriteLine(x);
Result
<book pubDate="July 31, 2006" />
------------------------------------------------------

XElement x= new XElement("book", "hi how are you",new XAttribute("pubDate", "July 31, 2006"));
Console.WriteLine(x);
Result
<book pubDate="July 31, 2006">hi how are you</book>
------------------------------------------------------
XElement book = new XElement("book",new XAttribute("publicationDate", "October 2005"));
Console.WriteLine(book);

Output
<book publicationDate="October 2005" />


------------------------------------------------------
XElement cricket = new XElement("cricket");
cricket.Add(new XElement("Team",
 new XAttribute("TeamName", "India"),
 new XElement("batsman", "sachin",new XAttribute("Rank",1)),
 new XElement("bowler", "ashwin")
)
);
XElement Team = new XElement("Team");
Team.Add( new XAttribute("TeamName", "AUS"),
  new XElement("batsman", "asdas"),
   new XElement("bowler", "asdasd")
);
cricket.Add(Team);
Console.WriteLine(cricket);

<cricket>
  <Team TeamName="India">
    <batsman Rank="1">sachin</batsman>
    <bowler>ashwin</bowler>
  </Team>
  <Team TeamName="AUS">
    <batsman>asdas</batsman>
    <bowler>asdasd</bowler>
  </Team>
</cricket>
------------------------------------------------------

cricket.Add(new XElement("Team",
    new XAttribute("TeamName", "India"),
    new XElement("batsman", "sachin",new XAttribute("Rank",1)),
    new XElement("bowler", "ashwin")
  ),
  new XElement("Team",
    new XAttribute("TeamName", "AUS"),
    new XElement("batsman", "sdf",new XAttribute("Rank",1)),
    new XElement("bowler", "sdf")
  )
);
Console.WriteLine(cricket);

<cricket>
  <Team TeamName="India">
    <batsman Rank="1">sachin</batsman>
    <bowler>ashwin</bowler>
  </Team>
  <Team TeamName="AUS">
    <batsman Rank="1">sdf</batsman>
    <bowler>sdf</bowler>
  </Team>
</cricket>

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

XElement book = new XElement("book");
book.Add(new XElement("author", "Don Box"));
book.Add(new XElement("title", "Essential .NET"));

XElement bag = new XElement("bag");
bag.Add(book);
Console.WriteLine(bag);

<bag>
  <book>
    <author>Don Box</author>
    <title>Essential .NET</title>
  </book>
</bag>
------------------------------------------------------
XElement books = XElement.Parse(
@"<books>
<book>
<title>abc</title>
<author>xxx</author>
</book>
</books>");
books.Element("book").Element("author").ReplaceNodes("foo");

Console.WriteLine(books);

<books>
  <book>
    <title>abc</title>
    <author>foo</author>
  </book>
</books>
------------------------------------------------------

XElement books = XElement.Parse(
@"<books>
 <book>
  <title>LINQ in Action</title>
  <author>Steve Eichert</author>
 </book>
</books>");
books.Element("book").SetElementValue("author", "foo");
Console.WriteLine(books);

<books>
  <book>
    <title>LINQ in Action</title>
    <author>foo</author>
  </book>
</books>
------------------------------------------------------

XElement books = XElement.Parse(
@"<books>
<book>
<title>aaa</title>
<author>bbb</author>
</book>
</books>");
books.Element("book").ReplaceNodes(
new XElement("title", "Ajax in Action"),
new XElement("author", "no")
);

Console.WriteLine(books);

<books>
  <book>
    <title>Ajax in Action</title>
    <author>no</author>
  </book>
</books>

------------------------------------------------------
public void FetchFunctionInfo(string functionid)
{
XElement xEle = XElement.Load(Server.MapPath("~\\images\\joblist\\FunctionalDesc.xml"));

var emp = xEle.Descendants("function").Where(func => (string)func.Attribute("functionid") == functionid);

 var emps = from nm in xEle.Descendants("function")
                           where (string)nm.Attribute("functionid") == functionid
                           select nm;
         foreach (var item in emp)
              Response.Write(item);
      }

September 30, 2016

local admin rights required for software developer

  • Locally site publish and test 
  • Developers toolsets are often updated very regularly. Graphics libraries, code helpers, visual studio updates; they end up having updates coming out almost weekly that need to be installed. Desktop support usually gets very tired of getting 20 tickets every week to go install updated software on all the dev machines so they just give the devs admin rights to do it themselves.
  • Debugging / Testing tools sometimes need admin rights to be able to function. No admin access means developers can’t do their job of debugging code. Managers don't like that.
  • For configuring TNS files
  •  

Data control in asp.net


Supported Funcationalities
ControlPagingData GroupingProvide Flexible LayoutUpdate,DeleteInsertSorting
ListViewsupportedsupportedsupportedsupportedsupportedsupported
GridViewsupportedNot supportedNot SupportedsupportedNot Supportedsupported
DataListNot supportedsupportedsupportedNot supportedNot supportedNot supported
RepeaterNot supportedNot supportedsupportedNot supportedNot supportedNot supported

* Supported: means that it's provided out of the box without any custom code or hacks.
* Not Supported: means that it's not provided out of the box by the control but it could be possible to implement it using custom code \ hacks.
The GridView : it supports paging but it doesn't provide a flexible layout , since its mainly used to display the data in a table based layout.And If we looked at data inserting , the Gridview doesn't have a built in support for inserting data( since it doesn't call the insert method of it underlying data source when you click on a button with a CommadName set to "Insert" ).
The DataList : it support data grouping ( through its RepeatColumns property) , but it doesn't have a built in support for paging,inserting ,deleting , updating the data. and if you looked at its laout , you will find that by default  the datalist renders as html table and you will have to set its flowLayout to "Flow" to stop that behaviour.
The Repeater control : you will find that it provides a flexible layout but it doesn't support data grouping ,inserting,deleting , updating  and paging through the data .

Summary :
The ListView control was added to provide a rich data control that can support all the required functionalities at the same time , so now you can easily display a fully customizable layout that supports Grouping,paging , inserting , deleting , updating and sorting the data.