Thursday, December 29, 2011

Asp.net tips and tricks

While testing, you can have emails sent to a folder on your computer instead of an SMTP server. Put this in your web.config:

<system.net>
     <mailSettings>
        <smtp deliveryMethod="SpecifiedPickupDirectory">
            <specifiedPickupDirectory pickupDirectoryLocation="c:\Temp\" />
        </smtp>
    </mailSettings>
</system.net>


HttpContext.Current always gives you access to the current context's Request/Response/etc., even when you don't have access to the Page's properties (e.g., from a loosely-coupled helper class).

You can continue executing code on the same page after redirecting the user to another one by calling Response.Redirect(url, false )

You don't need .ASPX files if all you want is a compiled Page (or any IHttpHandler). Just set the path and HTTP methods to point to the class in the <httpHandlers> element in the web.config file.

A Page object can be retrieved from an .ASPX file programmatically by calling PageParser.GetCompiledPageInstance(virtualPath,aspxFileName,Context)


Add this to your web.config for much faster compilation (post 3.5SP1).

<compilation optimizeCompilations="true">

Retail mode at the machine.config level:

<configuration>
  <system.web>
    <deployment retail="true"/>
  </system.web>
</configuration>

This overrides the web.config settings to enforce debug to false, turns custom errors on and disables tracing. No more forgetting to change attributes before publishing - just leave them all configured for development or test environments and update the production retail setting.  Of course, you still want to build in Release mode.

You can use:

Request.Params[Control.UniqueId]
To get the value of a control before viewstate is initialized (Control.Text etc will be empty at this point). This is useful for code in Init.


You can use ASP.NET AJAX callbacks to web methods placed in ASPX pages. You can decorate a static method with the [WebMethod()] and [ScriptMethod()] attributes. For example:

[System.Web.Services.WebMethod()] 
[System.Web.Script.Services.ScriptMethod()] 
public static List<string> GetFruitBeginingWith(string letter)
{
        List<string> products = new List<string>() 
        { 
                "Apple""Banana""Blackberry""Blueberries""Orange""Mango""Melon""Peach"
        };

        return products.Where(p => p.StartsWith(letter)).ToList();
}

Now, in your ASPX page you can do this:

<form id="form1" runat="server">
        <div>
                <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
                <input type="button" value="Get Fruit" onclick="GetFruit('B')" />
        </div>
</form>
And call your server side method via JavaScript using:

    <script type="text/javascript">
        function GetFruit(l)
        {
                PageMethods.GetFruitBeginingWith(l, OnGetFruitComplete);
        }

        function OnGetFruitComplete(result)
        {
                alert("You got fruit: " + result);
         }
</script>


Check to see if the client is still connected, before starting a long-running task:

if (this.Response.IsClientConnected)
{
  // long-running task
}


Tag Mapping:
Tag mapping allows you to swap compatible controls at compile time on every page in your web application. A useful example is if you have a stock ASP.NET control, such as a DropDownList, and you want to replace it with a customized control that is derived from DropDownList. This could be a control that has been customized to provide more optimized caching of lookup data. Instead of editing every web form and replacing the built in DropDownLists with your custom version, you can have ASP.NET in effect do it for you by modifying web.config:

<pages>
<tagMapping>
   <clear />
   <add tagType="System.Web.UI.WebControls.DropDownList"
         mappedTagType="SmartDropDown"/>
  </tagMapping>
</pages>


You can use ASP.NET Comments within an .aspx page to comment out full parts of a page including server controls. And the contents that is commented out will never be sent to the client.

<%--
    <div>
        <asp:Button runat="server" id="btnOne"/>
     </div>
--%>

The Code Expression Builder
Sample markup:

Text = '<%$ Code: GetText() %>'
Text = '<%$ Code: MyStaticClass.MyStaticProperty %>'
Text = '<%$ Code: DateTime.Now.ToShortDateString() %>'
MaxLenth = '<%$ Code: 30 + 40 %>'
The real beauty of the code expression builder is that you can use databinding like expressions in non-databinding situations. You can also create other Expression Builders that perform other functions.

web.config:

<system.web>    
    <compilation debug="true">
        <expressionBuilders>
            <add expressionPrefix="Code" type="CodeExpressionBuilder" />
The cs class that makes it all happen:

[ExpressionPrefix("Code")]
public class CodeExpressionBuilder : ExpressionBuilder
{
    public override CodeExpression GetCodeExpression(
        BoundPropertyEntry entry,
        object parsedData,
        ExpressionBuilderContext context)
    {            
        return new CodeSnippetExpression(entry.Expression);
    }




IsDebuggingEnabled:

HttpContext.Current.IsDebuggingEnabled

This is great for determining which scripts to output (min or full versions) or anything else you might want in dev, but not in production.


MaintainScrollPositionOnPostBack:

MaintainScrollPositionOnPostback attribute in the @Page directive. It is used to maintain scroll position of an aspx page across postbacks.

Run ASP.Net outside of IIS or Visual Studio:

The whole runtime is packaged up and ready to be hosted in any process that wants to give it a try. Using ApplicationHost, HttpRuntime and HttpApplication classes, you too can grind up those .aspx pages and get shiny HTML output from them.

HostingClass host = ApplicationHost.CreateApplicationHost(typeof(HostingClass), 
                                            "/virtualpath""physicalPath");
host.ProcessPage(urlToAspxFile); 
And your hosting class:

public class HostingClass : MarshalByRefObject
{
    public void ProcessPage(string url)
    {
        using (StreamWriter sw = new StreamWriter("C:\temp.html"))
        {
            SimpleWorkerRequest worker = new SimpleWorkerRequest(url, null, sw);
            HttpRuntime.ProcessRequest(worker);
        }
                    
    }
}



Request.IsLocal Property:

It indicates whether current request is coming from Local Computer or not.

if( Request.IsLocal )
{
   LoadLocalAdminMailSettings();
}
else
{
   LoadServerAdminMailSettings();
}


By default web form page inherits from System.Web.UI.Page class. There is a way to constraint any page to inherit from a base class. Simply add a new line on your web.config:

<system.web>
    <pages pageBaseType="MyBasePageClass" />
</system.web>
 

Thursday, December 8, 2011

LINQ / Refletion Typed List / Pass values across Form's without Session,Application,Querstring,POST

 

LINQ to SQL

 

using (BaseDataContext context = new BaseDataContext())

            {

                var result = context.GetPublicOfficialMasterData(

                    DatabaseConstants.GovernmentOwnershipEntityValue,

                    DatabaseConstants.SanctionEntityValue,

                    DatabaseConstants.CompanyStatusEntityValue,

                    DatabaseConstants.EmployeeStatusEntityValue,

                    DatabaseConstants.CountryEntityValue);

                List<BaseMasterData> all = result.ToList();

               

                var sanction = from res in result

                               where res.EntityName == DatabaseConstants.SanctionEntityValue

                               select res;

                //masterEntities = (BaseCollection<BaseMasterDataEntity>)result.ToList<BaseMasterDataEntity>();

            }

 

public class BaseDataContext : DataContext

    {

        public BaseDataContext()

            : base(ConfigurationManager.ConnectionStrings["CDD"].ConnectionString) { }

 

        [Function(Name = "dbo.uspGetPublicOfficialMasterData")]

        public ISingleResult<BaseMasterData> GetPublicOfficialMasterData(

            [Parameter(Name = "GovernmentOwnershipEntityName", DbType = "NChar(25)")] string governmentOwnership,

            [Parameter(Name = "SanctionEntityName", DbType = "NChar(25)")] string sanction,

            [Parameter(Name = "CompanyStatusEntityName", DbType = "NChar(25)")] string companyStatus,

            [Parameter(Name = "EmployeeStatusEntityName", DbType = "NChar(25)")] string employeeStatus,

            [Parameter(Name = "CountryEntityName", DbType = "NChar(25)")] string country)

        {

            IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())),

                governmentOwnership, sanction, companyStatus, employeeStatus, country);

            return ((ISingleResult<BaseMasterData>)(result.ReturnValue));

        }

    }

 

 

 

Create Typed list via reflection

 

AddMaterEntityByEntityType(ref masterEntities,

                                drMasterData.Select(string.Format(query, DatabaseConstants.CountryEntityValue)),

                                typeof(Country));

 

private void AddMaterEntityByEntityType(ref BaseCollection<BaseMasterDataEntity> masterEntities,

            DataRow[] dataRow, Type type)

        {

            BaseMasterDataEntity entity = default(BaseMasterDataEntity);

            Type typeList = typeof(List<>);

            Type actualType = typeList.MakeGenericType(type);

            var obj = (List<BaseMasterDataEntity>)Activator.CreateInstance(actualType);

 

            foreach (DataRow item in dataRow)

            {

                entity = CreateMasterEntityByType(item["EntityName"].ToString());

                entity.ID = Convert.ToInt32(item["ID"]);

                entity.Description = Convert.ToString(item["Name"]);

                obj.Add(entity);

            }

            masterEntities.AddRange(obj);

        }

 

 

Avoid querstring, session, application, to pass variables across pages

 

Add hidden field on the page

<asp:HiddenField ID="hdnActionOnCode" runat="server" />

 

Set control client ID into session and replace _ with $

public string CodeKey

        {

            get { return ((string)Session[UIConstants.POCodeKey]).Replace('_', '$'); }

            set { Session[UIConstants.POCodeKey] = value; }

        }

 

Modify hidden field value to be passed onto other page before page request

function SetCode(code) {

        var hdnField = document.getElementById('<%= hdnActionOnCode.ClientID %>');

        hdnField.value = code;

    }

 

Access field and value as part of Request.Form.AllKeys

public string POCode {

            get {

                return Request.Form.AllKeys.Contains(CodeKey) ? Request.Form[CodeKey].ToString() : string.Empty;

            }

        }

Friday, August 19, 2011

How to hunt down applications via their port numbers

Let’s say that we are looking for port 80 — IIS, Apache and other web servers listen in port 80, so when you are having problems starting Apache, this technique will be useful. Here is the command.
C:\>netstat -aon | findstr 0.0:80
-a means list all active connections and their ports. -o means include their process IDs. -n means display the port numbers numerically.
The pipe symbol ( | ) means, that instead of the result of netstat being displayed on the screen, feed it’s result to the findstr process — we are looking specifically for the line which has 0.0:80 — you actually don’t need findstr, but I don’t want to scroll down and hunt down manually which app is using port 80. You might see something like this.
TCP 0.0.0.0:80 0.0.0.0:0 LISTENING 560
Aha! now we know that process 560 is using port 80 (that last column right there, is the process ID), you could press CTRL-ALT-DEL now to show the process window, and manually look up which app has the process ID 560, or you could enter ..
C:\>tasklist | findstr 560
tasklist is another Windows command line utility which shows you a list of all active processes, again I’d feed it to the findstr utility via the pipe operator, and voila — Skype is the culprit.
 
 

Tuesday, June 28, 2011

Everything about SQL Identity

create table players
( id int identity(1,1) not null,
name varchar(50))
 
insert into players values('vaaibhav')
insert into players values('vaaav')
 
select * from players
 
dbcc checkident (players, noreseed)
 
dbcc checkident (players, reseed, 10)
 
insert into players values('vav')
 
select * from players
 
 
create table experts
( id int identity(2,2) not null,
name varchar(50))
 
insert into experts values('vaaibhav')
insert into experts values('vaaav')
 
select * from experts
 

Friday, May 20, 2011

FW: Twitter And Facebook Integration Articles

 
 
 
 
Twitter:
 
 
Facebook:
 
 

FW: Microsoft Useful Articles

 
Managed Extensibility Framework (MEF):
 
Threading :
 
AppDomain:
 
MSDN Magazine
 
 

Friday, February 18, 2011

Outlook Macro and Digital Signature

Digital Signature
 
Setting the security level to medium or low affects macros coming from all
sources (like virus-infected emails). After some more research, I've found a
way to do this without reducing the security level.

1. Create a digital certificate for yourself
Windows XP: Start, All Programs, Microsoft Office Tools, Digital Certificate
for VBA Projects.
Windows 2000: Start, Programs, Microsoft Office Tools, Digital Certificate
for VBA Projects.
(If the SelfCert.exe file is not on your computer, you might need to install
it.)
Follow the instructions to create a certificate.

2. Sign the Macro
In Outlook: Tools, Macro, Visual Basic Editor.
In the Project Explorer, select the project you want to sign.
Click Tools, Digital Signature. Click Choose, select the certificate, click
OK twice. Save.

3. When you open or run the macro, you’ll get a security warning. Check
“Always trust macros from this source”.

Your digital signature/certificate can be used for macros in all Office
applications.
 
 
Outlook Macro
 
Goto     Tools -> Macro -> Visual Basic Editor (Alt + F11)
Select   "Microsoft Office Outlook Objects" -> "ThisOutlookSession"
Type in below code :
 
Public WithEvents myOlItems As Outlook.Items
 
 
Public Sub Application_Startup()
 
   ' Reference the items in the Inbox. Because myOlItems is declared
   ' "WithEvents" the ItemAdd event will fire below.
   Set myOlItems = Outlook.Session.GetDefaultFolder(olFolderInbox).Items
 
End Sub
 
 
Private Sub myOlItems_ItemAdd(ByVal Item As Object)
 
   ' If it's currently not between 9:00 A.M. and 5:00 P.M.
   If Time() < #9:00:00 AM# Or Time() > #5:00:00 PM# Then
 
      ' Check to make sure it is an Outlook mail message, otherwise
      ' subsequent code will probably fail depending on what type
      ' of item it is.
      If TypeName(Item) = "MailItem" Then
 
         ' Forward the item just received
         Set myForward = Item.Forward
 
         ' Address the message
         myForward.Recipients.Add "kadian.vaibhav@aol.in"
 
         ' Send it
         myForward.Send
 
      End If
 
   End If
 
   ' If it's currently not between 9:00 A.M. and 5:00 P.M.
   If Time() >= #9:00:00 AM# Or Time() <= #5:00:00 PM# Then
 
      ' Check to make sure it is an Outlook mail message, otherwise
      ' subsequent code will probably fail depending on what type
      ' of item it is.
      If TypeName(Item) = "MailItem" Then
 
         ' Forward the item just received
         Set myForward = Item.Forward
 
         ' Address the message
         myForward.Recipients.Add "vaibhav.kadian@aol.in"
 
         ' Send it
         myForward.Send
 
      End If
 
   End If
 
End Sub
 
 

Wednesday, February 9, 2011

DDE - Dynamic Data Exchange

Dynamic Data Exchange (DDE) is a technology for communication between multiple applications under Microsoft Windows or OS/2.
 
A list of methods of passing data between programs and which operating systems support them is to be found in Knowledgebase article Q95900 Interprocess Communication Mechanisms.
In additional to COM and DDE they are NetBIOS, Pipes, Sockets, Mailslots, Memory Mapped Files and WM_COPYDATA. Memory Mapped Files and WM_COPYDATA do not operate over a network. Only DDE and COM are mechanisms of the type in which multiple clients can connect to a single server. Named pipes are reported to be amongst the fastest ways of sending data between different computers.
 
DDE mechanism overview
Making the connection between a DDE server and a DDE client
DDE uses a hierarchy of three names, the SERVICE, the TOPIC and the ITEM. A DDE CONVERSATION is established using the service and topic names as a pair. It is convenient to name the pair a CHANNEL. It is roughly the equivalent of a telephone number. The item part of the name is used to identify the particular data or command being requested by the client once a conversation is established.
To establish a conversation a DDE client specifies the service/topic name pair (channel) it wishes to connect to. Windows broadcasts the request to all top level windows. The first server to accept is connected to the client and so a conversation is established.
The client may leave either the topic or the service name unspecified, or both. This is known as a WILDCONNECT. For example, if the topic name is not specified conversations may be established on all the topics supported by a server. If both are unspecified conversations may be established on all topics with all servers. It is up to the server whether to accept such a connection, and if so on what topics.
Unlike a telephone connection, any number of quite separate conversations may be in progress on the same channel, even between the same two applications. This is often done so that only one item of information or one type of command is handled by each conversation. There is no interaction at all between different conversations using the same pair of service and topic names.
Transactions within a DDE conversation
Just as the client application initiates the establishment of a conversation, it also initiates all the transactions. It can request data from the server as a once off (a REQUEST transaction), request being kept up to date about an item of data (an ADVISE or NOTIFY transaction), give commands to the server (an EXECUTE transaction) and send unsolicited data to the server (a POKE transaction). The client associates with all these transactions the item part of the identification. It informs the server of the data required by the client in a request transaction, the action to be taken by the server in an execute transaction or the data being passed to the server in a poke transaction.
It is also possible to use the item part of the name as the data itself, with the topic name indicating the context in which the data is to be used.
Raw DDE has no timing constraints except the order in which messages are sent. At the Windows message level, there is no distinction between synchronous and asynchronous transactions. Synchronous and asynchronous operation is a feature of the DDE management library, or DDEML.
 
What is DDE and why is it totally different from COM?
DDE sends data between applications using Windows messages according to a documented protocol. Saying that DDE is old-fashioned and is being replaced by COM is something you see repeated parrot fashion over and over again. DDE and COM do not work in the same way and they solve different problems. Here are some points of difference:
  • COM is synchronous, one party makes subroutine calls into the other and must wait until the call returns. If the called component is busy the caller is blocked until it becomes free. DDE is asynchronous, a well-programmed client sends a Windows message to the server and carries on processing. Windows holds the message and sends it to the server when the server is ready to process it.
  • COM is complex to program but powerful. The client can manipulate objects within the server as if they belonged to the client. DDE is straightforward to implement but all it can do is transmit data. It can only control another application because the recipient can treat data as a command.
  • COM works well when the client creates an instance of a server object or application for its own use. Programming a continuously running server, to which clients can attach when they wish, is possible but tricky. DDE of itself is incapable of creating objects (although OLE1 used it as a transport mechanism). The essence of DDE is that clients attach to an already running server.
  • Applications using COM almost always need support DLLs such as the VB runtimes or MFC. Programs using DDE can be mean and lean and do not need extra support DLLs.
  • COM interfaces are tightly specified and contained within the software component. Some documentation is normally built into the interface. The user of a COM component knows exactly which methods are available and how to call them. DDE interfaces are specified only in external documentation.
  • Because of the tight interface specification, upgrading COM components can be a nightmare. With DDE the server or client can be changed independently.
  • COM is frequently used to communicate with a DLL in the same process space (called an in-process server). Such as server is often termed an ActiveX control and has the extension OCX. Our DDClient and DDServer Visual Basic components are in-process servers. Using DDE to communicate between components of the same application is possible but has no benefits.
  • COM communication with a remote machine is called DCOM (Distributed COM). If you make a DCOM call to a remote machine which does not respond, your program (or at least the thread making the call) is stuck. DCOM has a fixed built-in timeout which you cannot change. DDE with a remote machine is called NETDDE, it is used by the Hearts game and Chat which come with Windows. Timeout is controlled by the program.
  • Under Windows 3.1 and 9x it is possible to crash the system by badly programmed DDE, because the message queue can be filled. NT does not crash in this way, COM does not suffer from the problem at all.
  • DDE is totally "Bit blind", neither the client nor server can tell whether the other application is 16-bit or 32-bit. Indeed, the server cannot know whether the client is on the same computer or not. Connecting 16 to 32 bit COM components is not usually possible.
It is easy to see from the above points why a DDE server is the most widely used way of providing data obtained from any form of hardware interface. In particular:
  • The server can run continuously.
  • It will probably serve a wide range of clients but can be updated without requiring them all to be recompiled.
  • It is immune from the problems associated with different versions of the system DLLs on different machines.
  • It can be small and self-contained.
  • Clients cannot interfere with the running of the server by being slow or busy.
 
 
Source & Related Links :