Tuesday, November 16, 2010

Amazon web service ISBN Search

String DESTINATION = "https://ecs.amazonaws.com/onca/soap?Service=AWSECommerceService";
String MY_AWS_ID = "ACCESS_ID";
String MY_AWS_SECRET = "SECRET_ID";



ItemSearchRequest objRequest = new ItemSearchRequest();
objRequest.SearchIndex = "Books";
objRequest.Power = "ISBN:9780557230648";
objRequest.ResponseGroup = new string[] { "Small", "AlternateVersions", "Large", "Medium", "Offers" };
objRequest.Sort = "salesrank";



ItemSearchRequest[] requests = new ItemSearchRequest[] { objRequest };

ItemSearch itemSearch = new ItemSearch();
itemSearch.AWSAccessKeyId = MY_AWS_ID;
itemSearch.Request = requests;



// create an instance of the serivce
AWSECommerceService api = new AWSECommerceService();

// set the destination
api.Destination = new Uri(DESTINATION);

// apply the security policy, which will add the require security elements to the
// outgoing SOAP header
AmazonHmacAssertion amazonHmacAssertion = new AmazonHmacAssertion(MY_AWS_ID, MY_AWS_SECRET);
api.SetPolicy(amazonHmacAssertion.Policy());

// make the call and print the title if it succeeds
try
{

ItemSearchResponse response = api.ItemSearch(itemSearch);
Items info = response.Items[0];
Item[] items = info.Item;
for (int i = 0; i < items.Length; i++) { Label1.Text += "Book Title: " + items[i].ItemAttributes.Title.ToString() + "<br />";} } catch (Exception ex) { Label1.Text += ex.Message.ToString(); }

Note:-
==================================================
AmazonHmacAssertion class is available in client project of below link
http://associates-amazon.s3.amazonaws.com/signed-requests/samples/amazon-product-advt-api-sample-csharp-soap.zip

Tuesday, October 5, 2010

configure log4Net

Web.Config:-


under configsection

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>

<log4net>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
<param name="File" value="logs\\error_04112009.log" />
<param name="AppendToFile" value="true"/>
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%-5p%d{yyyy-MM-dd hh:mm:ss} - %m%n" />
</layout>
</appender>
<logger name="File">
<level value="All" />
<appender-ref ref="LogFileAppender" />
</logger>
</log4net>


Global.asax:-

void Application_Start(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
}

Monday, September 27, 2010

Paging using SP

SET @StartRow = (@PageIndex - 1) * @PageSize + 1
SET @EndRow = @StartRow + @PageSize - 1

SET @StartRow = (@PageIndex - 1) * @PageSize + 1
SET @EndRow = @StartRow + @PageSize - 1

SET @TotalRec = Select Count(*) from Test

-- If StartRow is less then Total Records then fetch all records between startrow and endrow else ignore start row only consider endrow
IF @StartRow <= @TotalRecords SET @SQL = ' SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (ORDER BY '+@Sort+') as [RowNumber] from Test )T1 WHERE RowNumber >= @StartRow AND RowNumber <= @EndRow'

SET @ParmDefinition = N'@StartRow int,@EndRow int,@Sort nvarchar(50)';
EXECUTE sp_executesql @SQL,@ParmDefinition,@StartRow=@StartRow,@EndRow=@EndRow,@Sort=@Sort;

END
ELSE
BEGIN
SET @SQL = '
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (ORDER BY '+@Sort+') as [RowNumber]
from Test
)T1
WHERE RowNumber <= @EndRow'

SET @ParmDefinition = N'@StartRow int,@EndRow int,@Sort nvarchar(50)';
EXECUTE sp_executesql @SQL,@ParmDefinition,@StartRow=@StartRow,@EndRow=@EndRow,@Sort=@Sort;
END



RETURN @TotalRec

paging for repeater

if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
PagedDataSource pgitems = new PagedDataSource();
DataView dv = new DataView(ds.Tables[0]);
pgitems.DataSource = dv;
pgitems.AllowPaging = true;
pgitems.PageSize = int.Parse(hidPageSize.Value.ToString());
pgitems.CurrentPageIndex = PageNumber;
if (pgitems.PageCount > 1)
{
rptTopPages.Visible = true;
ArrayList pages = new ArrayList();
for (int i = 0; i < pgitems.PageCount; i++) pages.Add((i + 1).ToString()); rptTopPages.DataSource = pages; rptTopPages.DataBind(); } else { rptTopPages.Visible = false; } rptItem.DataSource = pgitems; rptItem.DataBind(); ASPX


<asp:Repeater ID="rptTopPages" runat="server" OnItemCommand="rptPages_ItemCommand">
<HeaderTemplate>
<table cellpadding="0" cellspacing="0" border="0">
<tr class="text">
<td>
<b>Page:</b>&nbsp;
</td>
<td>
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton ID="btnPage" CssClass="ActiveNode" CommandName="Page" Visible='<%# SetVisible(Container.DataItem,true) %>'
CommandArgument="<%# Container.DataItem %>" runat="server"><%# Container.DataItem %></asp:LinkButton><asp:Label
ID="lblPage" runat="server" Text='<%# Container.DataItem %>' CssClass="InActiveNode"
Visible='<%# SetVisible(Container.DataItem,false) %>'></asp:Label>&nbsp;
</ItemTemplate>
<FooterTemplate>
</td> </tr> </table>
</FooterTemplate>
</asp:Repeater>

Thursday, September 23, 2010

Use FormsAuthenticationTicket to save LoggedIn UserID

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2,id,DateTime.Now,DateTime.Now.AddMinutes(10), false, testid);

string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
HttpContext.Current.Response.Cookies.Add(cookie);


Fetch Data from FormsAuthenticationTicket :-


if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.AuthenticationType == "Forms")
{
System.Web.Security.FormsIdentity formsIdentity = default(System.Web.Security.FormsIdentity);
formsIdentity = (System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity;
string str = formsIdentity.Ticket.UserData;
}
}

Reflection + set/Get property

foreach (PropertyDescriptor properties in prop)
{
objClass.GetType().GetProperty(properties.Name).SetValue(objClass, objlistObject.GetType().GetProperty(properties.Name).GetValue(objlistObject, null), null);
}

Convert Datatable to List using reflection

public static List ConverttoList(DataTable dbTaskTable)
{
List lsttaskListBE = new List();
TaskListBE objtaskListBE = new TaskListBE();
PropertyDescriptorCollection prop = TypeDescriptor.GetProperties(objtaskListBE);
foreach(DataRow datarow in dbTaskTable.Select())
{
objtaskListBE=new TaskListBE();
foreach (PropertyDescriptor properties in prop)
{
objtaskListBE.GetType().GetProperty(properties.Name).SetValue(objtaskListBE, (((datarow[properties.Name])==System.DBNull.Value)?null:datarow[properties.Name]), null);
}
lsttaskListBE.Add(objtaskListBE);
}
return lsttaskListBE;
}

Create Array through reflection

// Create Array
Array objArray = Array.CreateInstance(objClass.GetType(), listCount);

//Set it's value
objArray.SetValue(objClass, j);

Call webservice without adding web reference

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

//Added for samplecode
using System.CodeDom.Compiler;
using System.Security.Permissions;
using System.Web.Services.Description;
using System.Reflection;
using System.CodeDom;
using System.Diagnostics;

namespace DynamicSoap
{

public static class DynamicWebService
{

public static Object CallWebService(string webServiceAsmxUrl,
string serviceName, string methodName, object[] args)
{

try
{
System.Net.WebClient client = new System.Net.WebClient();

//-Connect To the web service
System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");

//Read the WSDL file describing a service.
ServiceDescription description = ServiceDescription.Read(stream);

//Load the DOM

//--Initialize a service description importer.
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12"; //Use SOAP 1.2.
importer.AddServiceDescription(description, null, null);

//--Generate a proxy client.

importer.Style = ServiceDescriptionImportStyle.Client;
//--Generate properties to represent primitive values.

importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;

//Initialize a Code-DOM tree into which we will import the service.
CodeNamespace codenamespace = new CodeNamespace();
CodeCompileUnit codeunit = new CodeCompileUnit();
codeunit.Namespaces.Add(codenamespace);

//Import the service into the Code-DOM tree.
//This creates proxy code that uses the service.

ServiceDescriptionImportWarnings warning = importer.Import(codenamespace, codeunit);

if (warning == 0)
{

//--Generate the proxy code
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

//--Compile the assembly proxy with the
// appropriate references
string[] assemblyReferences = new string[] {
"System.dll",
"System.Web.Services.dll",
"System.Web.dll",
"System.Xml.dll",
"System.Data.dll"};

//--Add parameters
CompilerParameters parms = new CompilerParameters(assemblyReferences);
parms.GenerateInMemory = true; //(Thanks for this line nikolas)
CompilerResults results = provider.CompileAssemblyFromDom(parms, codeunit);

//--Check For Errors
if (results.Errors.Count > 0)
{

foreach (CompilerError oops in results.Errors)
{
System.Diagnostics.Debug.WriteLine("========Compiler error============");
System.Diagnostics.Debug.WriteLine(oops.ErrorText);
}
throw new Exception("Compile Error Occured calling WebService.");
}

//--Finally, Invoke the web service method
Object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
return mi.Invoke(wsvcClass, args);

}
else
{
return null;
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}

Reference link :- http://www.codeproject.com/KB/webservices/webservice_.aspx

Monday, September 13, 2010

asp.net Menu not working at chrome

To solve this you will need to tell .net the capabilities of the browser. For .net 2.0 & above you need to create a new browers file with the capabilities and upload it to your server.

In VS2008 Solution Explorer right click your application and add the “ASP.Net Folder” App_Browsers if you don’t already have it.
Add a New “Browser File” item to this special folder and call it safari.browser (if fixing the problem for Chrome)
Delete all the default stuff VS put in this file and replace it with the following:

<browsers>
<browser refID="safari1plus">
<controlAdapters>
<adapter controlType="System.Web.UI.WebControls.Menu" adapterType="" />
</controlAdapters>
</browser>
</browsers>

Save your file & test locally to see if all is well.
Now for the annoying bit. Upload the new app_browser folder & file to your production server, if you have used the “copy web site” menu option to upload or sharepoint or frontpage, these will create a new folder under app_browsers called vti_cnf
Manually delete the vti_cnf folder under app_browser on your production server. If you don’t you’ll get “Parse error: Data at the root level is invalid. Line 1, position 1.” in your new safari.browser file.
Remember to manually delete this vti_cnf folder everytime you make a change to the app_browser folder or contained files.
So there you go, how to solve the control rendering problems with Google’s Chrome.

For original post you can visit

http://fabenterprises.wordpress.com/2009/03/21/aspnet-menu-not-rendering-correctly-in-googles-chrome/

Tuesday, September 7, 2010

Sunday, September 5, 2010

Fire ItemCommand event of repeater from <div> click or <tr> click using javascript

HTML:-

<asp:Repeater ID="rpt" runat="server" OnItemCommand="rpt_ItemCommand" OnItemCreated="rpt_ItemCreated">
<HeaderTemplate>
<table width="100%" cellpadding="0" cellspacing="0">
</HeaderTemplate>
<ItemTemplate>
<tr onclick='javascript:FireItemCommand(<%#DataBinder.Eval(Container, "ItemIndex", "")%>)'
style="cursor: pointer">
<td>
<%# Eval("Name") %>
</td>
<td>
<asp:LinkButton ID="lnkDim" runat="server" Text="lnk123" CommandArgument='<%# Eval("Name") %>'></asp:LinkButton>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>

Javascript:-
function FireItemCommand(index) {

__doPostBack('rpt$ctl0' + parseInt(index + 1).toString() + '$lnkDim', '');

}

Monday, August 30, 2010

Custom Modal popup

Css : 
.ModalPopupStyle{background-color: #FFFFFF;}
        .modalBackground
        {
            background-color: Black;
            filter: alpha(opacity=70);
            opacity: 0.7;
        }
        .RoundedCornerTop_Left
        {
            background-image: url(newimages/top_left.png);
            width: 10px;
            height: 21px;
            background-repeat: no-repeat;
        }
        .RoundedCornerBottom_Left
        {
            background-image: url(newimages/bottom_left.png);
            width: 10px;
            height: 10px;
            background-repeat: no-repeat;
        }
        .RoundedCornerBottom_Right
        {
            background-image: url(newimages/bottom_right.png);
            width: 21px;
            height: 10px;
            background-repeat: no-repeat;
        }

Javascript:
function ShowModalPopup(div) {
            $("modalbackgroundElement").style.width = "1261px"; $("modalbackgroundElement").style.position = "fixed"; $("modalbackgroundElement").style.left = "0px"; $("modalbackgroundElement").style.top = "0px"; $("modalbackgroundElement").style.zIndex = "10000"; $("modalbackgroundElement").style.width = screen.width + "px"; $("modalbackgroundElement").style.height = screen.height + "px"; var w = (getWindowWidth() - document.getElementById(div).style.width.substring(0, document.getElementById(div).style.width.indexOf("px"))) / 2; var h = (getWindowHeight() - document.getElementById(div).style.height.substring(0, document.getElementById(div).style.height.indexOf("px"))) / 2 + document.body.scrollTop; $(div).style.top = h + "px"; $(div).style.left = w + "px"; $(div).style.display = "block"; $("modalbackgroundElement").style.display = "block"; $("divBack").style.top = $(div).style.top; $("divBack").style.left = $(div).style.left; $("divBack").style.width = $(div).style.width; $("divBack").style.height = $(div).style.height; $("divBack").style.zIndex = "10001"; $("divBack").style.position = "fixed"; $("divBack").style.margin = "10px"; $("divBack").style.display = "none"; poll_div = div; poll_left = w; poll_top = h;
            var myPageY = 0;
            if (document.all) { myPageY = document.documentElement.scrollTop; }
            else { myPageY = window.pageYOffset; }
            poll_h = myPageY;
            h = (getWindowHeight() - document.getElementById(div).style.height.substring(0, document.getElementById(div).style.height.indexOf("px"))) / 2;
            $(div).style.top = (h) + "px";
            return false;
        }
        function $(id) { if (id == "") { return null; } else { return document.getElementById(id); } }

        function getWindowHeight() {
            var windowHeight = 0; if (typeof (window.innerHeight) == 'number') { windowHeight = window.innerHeight; }
            else {
                if (document.documentElement && document.documentElement.clientHeight) { windowHeight = document.documentElement.clientHeight; }
                else { if (document.body && document.body.clientHeight) { windowHeight = document.body.clientHeight; } }
            }
            return windowHeight;
        }
        function getWindowWidth() {
            var windowWidth = 0; if (typeof (window.innerWidth) == 'number') { windowWidth = window.innerWidth; }
            else {
                if (document.documentElement && document.documentElement.clientWidth) { windowWidth = document.documentElement.clientWidth; }
                else { if (document.body && document.body.clientWidth) { windowWidth = document.body.clientWidth; } }
            }
            return windowWidth;
        }

HTML:
<div id="divBack" style="background-color: #000000; position: absolute; z-index: 100001;">
    </div>
    <div id="modalbackgroundElement" class="modalBackground">
    </div>

<div id="divModal" style="display: none; position: fixed; z-index: 100002; width: 275px;
        height: 200px;">
        <table cellpadding="0" cellspacing="0" border="0" width="275">
            <tr valign="bottom">
                <td class="RoundedCornerTop_Left" width="10px" height="21px">
                </td>
                <td style="background-image: url(newimages/space_cut12.png); background-repeat: repeat-x;
                    padding-right: 15px" valign="bottom" width="254" align="right">
                    <span id="required">* </span><span class="require23">Required fields</span>
                </td>
                <td valign="bottom" width="21">
                    <a href="#" style="text-decoration: none" onclick="javascript:return CloseContactForm();">
                        <img src="newimages/close_btn_16.png" alt="close" border="0" style="vertical-align: bottom"
                            width="21" height="21" /></a>
                </td>
            </tr>
            <tr valign="top" style="width: 254">
                <td colspan="3" class="ModalPopupStyle">
                    <uc1:TaskDetail ID="ContactDetails1" runat="server" strValue="2" />
                </td>
            </tr>
            <tr>
                <td class="RoundedCornerBottom_Left">
                </td>
                <td style="width: 254px; background-color: #fff">
                </td>
                <td class="RoundedCornerBottom_Right">
                </td>
            </tr>
        </table>
    </div>

Thursday, August 26, 2010

USING RECURSIVE COMMON TABLE EXPRESSIONS TO REPRESENT TREE STRUCTURES

Problem : 
Suppose if you have table structure which contains reference as same table for parent entry and you want to display data in table structure then below query will be useful.

Table Structure is:-
catid       catname                parentcatid
1             Cat1                     0
2             Cat2                     0
3             Cat3                     0
4             Cat1_sub1            1
5             Cat1_sub2            1
6             Cat1sub_sub         4
7             Cat2_sub1            2
8             Cat3_sub1            3
9             Cat2_subsub         7
10           Cat2_subsub         6

Desired output is:
Parentcatid                   Tree_Structure
0                                  Cat1
1                                  Cat1->Cat1_sub1
4                                  Cat1->Cat1_sub1->Cat1sub_sub
6                                  Cat1->Cat1_sub1->Cat1sub_sub->Cat2_subsub
1                                  Cat1->Cat1_sub2
0                                  Cat2
2                                  Cat2->Cat2_sub1
7                                  Cat2->Cat2_sub1->Cat2_subsub
0                                  Cat3
3                                  Cat3->Cat3_sub1

SQL Query:-

WITH supplytree AS
(SELECT catid, catname, parentcatid, CAST(catname As varchar(1000)) As si_item_fullname
FROM #tempsample
WHERE parentcatid = 0 
UNION ALL
SELECT si.catid,si.catname,
si.parentcatid,
CAST(sp.si_item_fullname + '->' + si.catname As varchar(1000)) As si_item_fullname
FROM #tempsample As si
INNER JOIN supplytree AS sp
ON (si.parentcatid = sp.catid)
)
SELECT parentcatid, si_item_fullname
FROM supplytree
ORDER BY si_item_fullname;

Wednesday, August 25, 2010

In SQL Server, How to combine multiple row result into one row

Suppose You have below data
Subjectid   Name
1               XYZ
1               ABC
1               PQR
2               RPA
2               PBA
3               TGB

Expected Result :
Subjectid  Name
1              XYZ, ABC, PQR
2              RPA, PBA
3              TGB


SQL Query:
Select Main.SubjectID,
Left(Main.Students,Len(Main.Students)-1) As "Students"
From(Select distinct ST2.SubjectID,
(Select ST1.Name + ',' AS [text()]
From dbo.Students ST1
Where ST1.SubjectID = ST2.SubjectID
ORDER BY ST1.SubjectID
For XML PATH ('')) [Students]
From dbo.Students ST2) [Main]

Tuesday, August 17, 2010

System.Runtime.Serialization.Json namespace is missing

You need to add reference of below dlls

System.Runtime.Serialization.dll
System.ServiceModel.dll
System.ServiceModel.Web.dll

Monday, August 16, 2010

Sharepoint - Apply Forms Authentication

http://technet.microsoft.com/hi-in/windowsserver/sharepoint/dd355701(en-us).aspx
http://www.simple-talk.com/dotnet/windows-forms/configuring-forms-authentication-in-sharepoint-2007/

Twitter Integration with asp.net

http://www.stardeveloper.com/articles/display.html?article=2009061701&page=1

Thursday, July 29, 2010

Sharepoint

http://sarangasl.blogspot.com/2009/09/custom-sharepoint-webparts.html
http://www.codeproject.com/KB/sharepoint/SharePointBasics.aspx#SP2007

Tuesday, May 18, 2010

security Exception solution

Error:-

Server Error in '/' Application. Security Exception Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.

Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.


Solution:-
changing the App pool identity to NetworkService / aspnet fixed it.
Additionally, enabling Load User Profile on the app pool also worked.

Wednesday, April 28, 2010

publish silverlight web application

http://www.codeproject.com/KB/silverlight/SilverlightWcfDatabase.aspx

How To Access Localhost Application URL Link in another Computer if There LAN Available

Here is One Interesting thing i Found when doing Programming.
if you want to access another Computer Link in your Computer to if LAN is available and if you find error Like internet Explorer could not find Page
Then do Following Steps:
1 : Go To Control Panel
2 : Then Select Windows FireWall
3 : select Tab "Exceptions"
4 : Add Port
5 :In Name write 'iis' or 'Localhost' and In Port numner write '80'

Sunday, April 25, 2010

Silver light child window links

http://www.silverlighttips.com/post/2009/09/24/Passing-value-from-child-window-to-parent-window.aspx



http://justgeeks.blogspot.com/2010/01/using-dataform-and-stored-procedures-in.html

Friday, April 23, 2010

Silverlight useful link for starting

http://www.microsoft.com/downloads/en/confirmation.aspx?familyId=9442b0f2-7465-417a-88f3-5e7b5409e9dd&displayLang=en


http://msdn.microsoft.com/en-us/magazine/cc895493.aspx?code=true&level=root,CS,SL20DSExample

http://www.silverlight.net/learn/tutorials/sqldatagrid-cs/

http://www.silverlight.net/content/samples/sl2/toolkitcontrolsamples/run/default.html

http://silverlight.codeplex.com/

Wednesday, March 31, 2010

Read mail of Inbox using IMAP

In one of my project i need to read all emails and if specified formatted mail is found then Use it.

Below is code to read.

public string IMAP_COMMAND_PREFIX = "IMAP00";
    public int IMAP_COMMAND_COUNT = 0;
    public string IMPAP_SUCCESS_RESPONSE = " OK";
    public string IMAP_NO_RESPONSE = " NO";
    public string IMAP_BAD_RESPONSE = " BAD";
    public string IMAP_COMMAND_EOL = "\r\n";
    public string IMAP_SEARCH_RESPONSE = "* SEARCH ";
    public string IMAP_UNSEEN_FLAG = "unseen";
    public string IMAP_CAPABILITY_COMMAND = "CAPABILITY";
    public string IMAP_LOGIN_COMMAND = "LOGIN";
    public string IMAP_LOGOUT_COMMAND = "LOGOUT";
    public string IMAP_SELECT_COMMAND = "SELECT INBOX";
    public string IMAP_SEARCH_COMMAND = "SEARCH";
    public string IMAP_UIDFETCH_COMMAND = "UID FETCH";
    public string IMAP_BODYSTRUCTURE_COMMAND = "BODYSTRUCTURE";
 protected void Page_Load(object sender, EventArgs e)
 {
  try {
   TcpClient tcpclient = new TcpClient(); // create an instance of TcpClient
   string strCommand = string.Empty;
   tcpclient.Connect("host name", 143); // HOST NAME IAMP SERVER and port number 143 for POP 
   Stream sslstream = tcpclient.GetStream();
   System.IO.StreamWriter sw = new StreamWriter(sslstream); // Asssigned the writer to stream
   System.IO.StreamReader reader = new StreamReader(sslstream); // Assigned reader to stream
   strCommand = IMAP_COMMAND_PREFIX + IMAP_COMMAND_COUNT.ToString() + " " + IMAP_CAPABILITY_COMMAND + IMAP_COMMAND_EOL;
    ReadResonse(reader, strCommand, sw);
    strCommand = IMAP_COMMAND_PREFIX + IMAP_COMMAND_COUNT.ToString() + " " + IMAP_LOGIN_COMMAND + " " + "EmailAddressID" + " " + "Email Password";
     ReadResonse(reader, strCommand, sw);
     strCommand = IMAP_COMMAND_PREFIX + IMAP_COMMAND_COUNT.ToString() + " " + IMAP_SELECT_COMMAND + IMAP_COMMAND_EOL;
      ReadResonse(reader, strCommand, sw);
      strCommand = IMAP_COMMAND_PREFIX + IMAP_COMMAND_COUNT.ToString() + " " + IMAP_SEARCH_COMMAND + " " + IMAP_UNSEEN_FLAG + IMAP_COMMAND_EOL;
      ReadResonse(reader, strCommand, sw);
      strCommand = IMAP_COMMAND_PREFIX + IMAP_COMMAND_COUNT.ToString() + " " + IMAP_SEARCH_COMMAND + " " + IMAP_LOGOUT_COMMAND + IMAP_COMMAND_EOL;
      ReadResonse(reader, strCommand, sw);

        }
        catch (Exception ex)
        {
        }

    }
    public void ReadResonse(StreamReader reader, string strCommand, StreamWriter swriter)
    {
        try
        {
            swriter.WriteLine(strCommand);
            swriter.Flush();
            bool IsLastSuccess = false;
            string strResponse = string.Empty;
            while ((strResponse = reader.ReadLine()) != null)
            {

                if (strResponse.StartsWith(IMAP_COMMAND_PREFIX + IMAP_COMMAND_COUNT.ToString() + IMPAP_SUCCESS_RESPONSE)) // find the success character in line
                {
                    break;
                }
                else if (strResponse.StartsWith(IMAP_COMMAND_PREFIX + IMAP_COMMAND_COUNT.ToString() + IMAP_NO_RESPONSE)) // find the failure character in line
                {

                    break;
                }
                else if (strResponse.StartsWith(IMAP_COMMAND_PREFIX + IMAP_COMMAND_COUNT.ToString() + IMAP_BAD_RESPONSE)) // find the failure character in line
                {
                    break;
                }
                else if (strResponse.StartsWith(IMAP_COMMAND_PREFIX + IMAP_COMMAND_COUNT.ToString() + IMAP_BAD_RESPONSE)) // find the failure character in line
                {
                    break;
                }
                else if (strResponse.StartsWith(IMAP_SEARCH_RESPONSE)) // find the unread mail
                {
                    string strTempUnread = strResponse.Substring(strResponse.IndexOf(IMAP_SEARCH_RESPONSE) + IMAP_SEARCH_RESPONSE.Length);
                    string[] strArray = strTempUnread.Split(" ".ToCharArray());
                    string strSearch = string.Empty;
                    while ((strSearch = reader.ReadLine()) != null)
                    {
                        if (strSearch.StartsWith(IMAP_COMMAND_PREFIX + IMAP_COMMAND_COUNT.ToString() + IMPAP_SUCCESS_RESPONSE))
                        {
                            IsLastSuccess = true;
                            break;
                        }
                    }

                    for (int i = 0; i < strArray.Length; i++)
                    {

                           //read header of email
                        swriter.WriteLine(IMAP_COMMAND_PREFIX + i.ToString() + " " + "FETCH " + strArray[i].ToString() + " BODY[HEADER.fields (from)]\r\n"); // this will retrive your first email 
                        swriter.Flush();
                        string strTemp = string.Empty;
                        while ((strTemp = reader.ReadLine()) != null)
                        {
                            if (strTemp.StartsWith(IMAP_COMMAND_PREFIX + i.ToString() + IMPAP_SUCCESS_RESPONSE))
                            {
                                break;
                            }
                            else if (strTemp.StartsWith(IMAP_COMMAND_PREFIX + i.ToString() + IMAP_NO_RESPONSE)) // find the failure character in line
                            {

                                break;
                            }
                            else if (strTemp.StartsWith(IMAP_COMMAND_PREFIX + i.ToString() + IMAP_BAD_RESPONSE)) // find the failure character in line
                            {
                                break;
                            }
                            else if (strTemp.StartsWith(IMAP_COMMAND_PREFIX + i.ToString() + IMAP_BAD_RESPONSE)) // find the failure character in line
                            {
                                break;
                            }                           

                        }

// read body of email
                        swriter.WriteLine(IMAP_COMMAND_PREFIX + i.ToString() + " " + " FETCH " + strArray[i].ToString() + " BODY[TEXT]\r\n"); // this will retrive your first email 
                        swriter.Flush();
                        while ((strTemp = reader.ReadLine()) != null)
                        {
                            if (strTemp.StartsWith(IMAP_COMMAND_PREFIX + i.ToString() + IMPAP_SUCCESS_RESPONSE))
                            {
                                break;
                            }
                            else if (strTemp.StartsWith(IMAP_COMMAND_PREFIX + i.ToString() + IMAP_NO_RESPONSE)) // find the failure character in line
                            {

                                break;
                            }
                            else if (strTemp.StartsWith(IMAP_COMMAND_PREFIX + i.ToString() + IMAP_BAD_RESPONSE)) // find the failure character in line
                            {
                                break;
                            }
                            else if (strTemp.StartsWith(IMAP_COMMAND_PREFIX + i.ToString() + IMAP_BAD_RESPONSE)) // find the failure character in line
                            {
                                break;
                            }
                        }

             }
}
   if (IsLastSuccess == true)
                    break;
 }

            IMAP_COMMAND_COUNT++;
        }
        catch (Exception ex)
        {
            log4net.ILog logger = log4net.LogManager.GetLogger("File");
            logger.Error("Lead Convertor + ReadResonse :" + ex.Message);
        }
    }
}


Beloow link for IMAP Commands http://bobpeers.com/technical/telnet_imap.php
Happy coding :-)

Wednesday, March 24, 2010

Create Excel file also use various formulas with in it

In one project has requirement that need to create excel file through coding and need to use various excel formals for it.Below is code for it.


FileStream fs = new FileStream(@"D:\Test\TestExcel.xls", FileMode.Create);
        StreamWriter sr = new StreamWriter(fs);
        Response.ContentType = "application/ms-excel";
        StringBuilder sb = new StringBuilder();
        sb.Append("<table>");
        sb.Append("<tr><td><font face='Arial' color='black' size='2'><b>Name</b></font></td>");
        sb.Append("<td><font face='Arial' color='black' size='2'><b>Amount</b></font></td></tr>");
        for (int i = 0; i < 10; i++)
        {
            sb.Append("<tr>");
            sb.Append("<td align='center' vertical-align='middle'>" + "<font face='Arial' color='black' size='2'>Name12</font></td>");
            sb.Append("<td align='center' vertical-align='middle'>" + "<font face='Arial' color='black' size='2'>" + i.ToString() + "</font></td>");
            sb.Append("</tr>");

        }
        sb.Append("<tr>");
        sb.Append("<td>Total</td>");
        sb.Append("<td>=SUM(B1:B11)</td></tr>");
        sb.Append("</table>");
        sr.WriteLine(sb.ToString());
        sr.Close();
        fs.Dispose();

Response.Clear();
Response.AddHeader("content-disposition", @"attachment; filename=Test.xls");
Response.Write(sb.ToString());


Happy coding ..

Tuesday, March 23, 2010

Syntax highlighter

Blogger needs some kind of syntax-highlighting plug-in before posting source code on a blog.

Today i am looking for it and i get great post through which i have learned syntax-highlighting.

Here are the steps:-

1) In th back end click on "NEW POST" or "CUSTOMIZE" then Go to "Layout" tab and click on "EDIT HTML" sub-tab.


2) Go to http://syntaxhighlighter.googlecode.com/svn/trunk/Styles/SyntaxHighlighter.css, then perform a "select all" and "copy". The css information is now in the clipboard.


3) Paste the css information at the end of the css section of your blogger html template before </b:skin>

4)Before the </head> tag, paste the following:

<!-- Add-in CSS for syntax highlighting -->
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shCore.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCpp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCSharp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCss.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushDelphi.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushJava.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushJScript.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushPhp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushPython.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushRuby.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushSql.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushVb.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushXml.js' type='text/javascript'></script>

remove lines for languages you'll never use


5) Before the </body> tag, insert the following:
<!-- Add-in Script for syntax highlighting -->
<script language='javascript'>
dp.SyntaxHighlighter.BloggerMode();
dp.SyntaxHighlighter.HighlightAll('code');
</script>


6) Use the "Preview" button to make sure your website is correct, then click "Save Template".

7) When composing a blog entry that contains source code, click the "Edit Html" tab and put your source code (with html-escaped characters) between these tags:

<pre name="code" class="cpp">
...Your html-escaped code goes here...
</pre>


substitute cpp with if you are using below languages

Language Aliases
C++ cpp, c, c++
C# c#, c-sharp, csharp
CSS css
Delphi delphi, pascal
Java java
Java Script js, jscript, javascript
PHP php
Python py, python
Ruby rb, ruby, rails, ror
Sql sql
VB vb, vb.net
XML/HTML xml, html, xhtml, xslt


You can do html-escaping by this link: http://www.accessify.com/tools-and-wizards/developer-tools/quick-escape/default.php


Source: http://heisencoder.net/2009/01/adding-syntax-highlighting-to-blogger.html

Dell laptop to switch functionality of function key

This drove me crazy for about 2 hours today. I swear I saw something in the control panel to switch between function keys and multimedia keys but alas I couldn't find it. Here's what you have to do: As the system in booting hit F2 to go to Setup. From there click 'System Configuration' then 'Function Key Behavior'. Switch to 'Fuction Key First' then hit the 'Apply' box, then 'Exit'. Now the function keys will work normaly and you can hold 'Fn' to use the multimedia fuctions.

Seriously, I searched through offline help for an hour and a half, then these forums for half an hour and I'm amazed at how hard it is to find out how to do something this simple. I'm just glad I've been messing around with computers since the days of DOS so I thought to look in the BIOS.

Friday, January 8, 2010

replace forward slash (\) using javascript

var strReplace = "C:\Temp\Temp1\Temp2\text.jpeg";

strReplace = strReplace.replace(new RegExp(/\\/g),"/");