using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; using System.Net.Mail; public partial class kalenderreminder : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //try //{ // DataTable dt = GetEvents().Tables[0]; // DataTable dt2 = new DataTable(); // if (dt != null) // { // MailMessage msgMail = new MailMessage(); // string s = null; // foreach (DataRow dr in dt.Rows) // { // dt2 = GetUser(dr["Worker"].ToString()).Tables[0]; // s += dr["EventDesc"].ToString(); // foreach(DataRow DataRow in dt2.Rows){ // msgMail.To = DataRow["E_MAIL"].ToString(); // msgMail.From = "noreply@mail.dk"; // msgMail.Subject = "New events from your personal calender..."; // msgMail.BodyFormat = MailFormat.Text; // //msgMail.Attachments.Add( //new MailAttachment(FileUpload1.ToString())); // msgMail.Body += "Event: " + "\n\n" + dr["EventDesc"].ToString() + "\r\n" + dr["EventDate"].ToString() + "\n\n\n"; // SmtpMail.SmtpServer = "smtp.something.com"; // if (s != null && s != "") // { // //SmtpMail.Send(msgMail); // } // // // } // } // AddRemided(); // } //}catch { } // EXAMPLE IF THERE WAS ONLY 1 USER DataTable dt = new DataTable(); dt = GetWorkers().Tables[0]; string loop = ";"; //maybe list or arraylist bool go = false; foreach (DataRow dr in dt.Rows) //while top 1 fra db { if (dt.Rows.Count == 0) break; foreach(string s in loop.Split(';')){ if(s == dr["Worker"].ToString()){ go = true; break; } } if (go == false) { MailMessage msgMail = new MailMessage(); try { DataTable tempdt = GetUserEmail(dr["Worker"].ToString()).Tables[0]; if (tempdt.Rows.Count != 0) { foreach (DataRow tempdr in tempdt.Rows) { if (tempdr["E_MAIL"].ToString() != "") msgMail.To.Add(new MailAddress(tempdr["E_MAIL"].ToString())); else throw new System.InvalidOperationException("No user found in DB!"); } }else throw new System.InvalidOperationException("No rows found in DB!"); } catch { DataTable tempdt = new DataTable(); tempdt = GetAllUsers().Tables[0]; foreach (DataRow tempdr in tempdt.Rows) msgMail.To.Add(new MailAddress(tempdr["E_MAIL"].ToString())); } msgMail.From = new MailAddress("noreply@mail.dk"); msgMail.Subject = "New events from your event calender..."; msgMail.BodyEncoding = System.Text.Encoding.UTF8; msgMail.IsBodyHtml = false; msgMail.Priority = MailPriority.High; //msgMail.Attachments.Add( //new MailAttachment(FileUpload1.ToString())); string events = null; { DataTable tempdt = GetUserEvents(dr["Worker"].ToString()).Tables[0]; foreach (DataRow tempdr in tempdt.Rows) { events = tempdr["EventDesc"].ToString(); if (events != null && events != "") { msgMail.Body += "Event: " + "\n\n" + tempdr["EventDesc"].ToString() + "\r\n" + tempdr["EventDate"].ToString() + "\n\n\n"; } else { msgMail.Body += "\r\n" + "Someone wrote empty event..." + "\n\n\n"; } } } SmtpClient SmtpServer = new SmtpClient("smtp.something.com"); if (msgMail.Body != null && msgMail.Body != "") { SmtpServer.Send(msgMail); AddRemided(dr["Worker"].ToString()); } loop += dr["Worker"].ToString() + ";"; go = false; dt = GetWorkers().Tables[0]; } } } private bool AddRemided(string user) { //You can Add Those Event In Same Dataset Again Or use Any One Of The Way //i.e. Store Your Event In DataBase Or Store It In Dataset MSSQLConn conn = new MSSQLConn(); SqlConnection sqlcn = new SqlConnection(conn.MSSQLString()); SqlCommand sqlcmd = new SqlCommand("Update kalender set mailreminder = 1 where convert(date, EventDate) = convert(datetime,(CONVERT(char(10), GETDATE(), 103)),103) and Worker = '" + user + "'", sqlcn); sqlcn.Open(); sqlcmd.CommandType = CommandType.Text; int _record; _record = sqlcmd.ExecuteNonQuery(); if (_record > 0) return true; else return false; } private DataSet GetWorkers() { try { MSSQLConn conn = new MSSQLConn(); SqlConnection sqlcn = new SqlConnection(conn.MSSQLString()); DataSet sqlds = new DataSet(); SqlDataAdapter sqlda = new SqlDataAdapter("Select Worker from kalender where convert(date, EventDate) = " + "convert(datetime," + "(CONVERT(char(10), GETDATE(), 103))" + ",103)" + " and mailreminder is null or mailreminder = 0 and EventDesc is not null", sqlcn); sqlda.Fill(sqlds); return sqlds; } catch (Exception ex) { //Response.Write(ex.Message.ToString()); } return null; } private DataSet GetUserEvents(string user) { try { MSSQLConn conn = new MSSQLConn(); SqlConnection sqlcn = new SqlConnection(conn.MSSQLString()); DataSet sqlds = new DataSet(); SqlDataAdapter sqlda = new SqlDataAdapter("Select * from kalender where convert(date, EventDate) = " + "convert(datetime," + "(CONVERT(char(10), GETDATE(), 103))" + ",103)" + " and (mailreminder is null or mailreminder = 0) and Worker = '" + user + "'", sqlcn); sqlda.Fill(sqlds); return sqlds; } catch (Exception ex) { //Response.Write(ex.Message.ToString()); } return null; } private DataSet GetAllUsers() { try { MSSQLConn conn = new MSSQLConn(); SqlConnection sqlcn = new SqlConnection(conn.MSSQLString()); DataSet sqlds = new DataSet(); SqlDataAdapter sqlda = new SqlDataAdapter("Select E_MAIL from Log_Users", sqlcn); sqlda.Fill(sqlds); return sqlds; } catch (Exception ex) { //Response.Write(ex.Message.ToString()); } return null; } private DataSet GetUserEmail(string user) { try { MSSQLConn conn = new MSSQLConn(); SqlConnection sqlcn = new SqlConnection(conn.MSSQLString()); DataSet sqlds = new DataSet(); SqlDataAdapter sqlda = new SqlDataAdapter("Select E_MAIL from Log_Users where Username = '" + user + "'", sqlcn); sqlda.Fill(sqlds); return sqlds; } catch (Exception ex) { //Response.Write(ex.Message.ToString()); } return null; } }
<!-- <form id="frmTest" method="post" runat="server"> <table width="100%" border="0"> <tr> <td> Repeater control with Paging functionality</td> </tr> <tr> <td> <asp:label id="lblCurrentPage" runat="server"></asp:label></td> </tr> <tr> <td> <asp:button id="cmdPrev" runat="server" text=" << " onclick="cmdPrev_Click"></asp:button> <asp:button id="cmdNext" runat="server" text=" >> " onclick="cmdNext_Click"></asp:button></td> </tr> </table> <table border="1"> <asp:repeater id="repeaterItems" runat="server"> <itemtemplate> <tr> <td> <b><%# DataBinder.Eval(Container.DataItem, "ItemName") %></b></td> <td> <b><%# DataBinder.Eval(Container.DataItem, "ItemDescription") %></b></td> <td> <b><%# DataBinder.Eval(Container.DataItem, "ItemPrice") %></b></td> <td> <b><%# DataBinder.Eval(Container.DataItem, "ItemInStock") %></b></td> </tr> </itemtemplate> </asp:repeater> </table> <p> </p> <asp:Button runat="server" Text="Cause a Postback" /> </form> <script runat="server" language="C#"> public int CurrentPage { get { // look for current page in ViewState object o = this.ViewState["_CurrentPage"]; if (o == null) return 0; // default to showing the first page else return (int) o; } set { this.ViewState["_CurrentPage"] = value; } } private void Page_Load(object sender, System.EventArgs e) { // Call the ItemsGet method to populate control, // passing in the sample data. ItemsGet(); } private void ItemsGet() { // Read sample item info from XML document into a DataSet DataSet Items = new DataSet(); Items.ReadXml(MapPath("Items.xml")); // Populate the repeater control with the Items DataSet PagedDataSource objPds = new PagedDataSource(); objPds.DataSource = Items.Tables[0].DefaultView; objPds.AllowPaging = true; objPds.PageSize = 3; objPds.CurrentPageIndex = CurrentPage; lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " of " + objPds.PageCount.ToString(); // Disable Prev or Next buttons if necessary cmdPrev.Enabled = !objPds.IsFirstPage; cmdNext.Enabled = !objPds.IsLastPage; repeaterItems.DataSource=objPds; repeaterItems.DataBind(); } private void cmdPrev_Click(object sender, System.EventArgs e) { // Set viewstate variable to the previous page CurrentPage -= 1; // Reload control ItemsGet(); } private void cmdNext_Click(object sender, System.EventArgs e) { // Set viewstate variable to the next page CurrentPage += 1; // Reload control ItemsGet(); } </script> -->
C#: void LinkButton_Click(object sender, EventArgs e) { LinkButton lbtnSender = (LinkButton)sender; DoAccordionPane(lbtnSender.ID.ToString()); } public void DoAccordionPane(string lnkbtnID) { DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory.ToString() "rootfolder/folder/" lnkbtnID "/"); FileInfo[] rgFiles = di.GetFiles("*.txt"); foreach (FileInfo fi in rgFiles) { AccordionPane pane2 = new AccordionPane(); pane2.HeaderContainer.Controls.Add(new LiteralControl(lnkbtnID " " fi.ToString().Split('.')[0])); List<string> result = new List<string>(); StreamReader re; using (re = new StreamReader(AppDomain.CurrentDomain.BaseDirectory.ToString() "rootfolder/folder/" lnkbtnID "/" fi.ToString(), new System.Text.UTF7Encoding())) { string input = null; while ((input = re.ReadLine()) != null) { result.Add(input); } re.Close(); } foreach (string s in result) { pane2.ContentContainer.Controls.Add(new LiteralControl(s)); MyAccordion.Controls.Add(pane2); } } } HTML: <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %> <script src="Scripts/jquery-1.2.6.js" type="text/javascript"></script> <style type="text/css"> .accordionHeader { border: 1px solid #2F4F4F; color: white; background-color: #719DDB; font-family: Arial, Sans-Serif; font-size: 12px; font-weight: bold; padding: 5px; margin-top: 5px; cursor: pointer; width:478px; height:18px; } .accordionContent { background-color: #DCE4F9; border: 1px dashed #2F4F4F; border-top: none; padding: 5px; padding-top: 10px; width:478px; height:0px; } </style> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <cc1:Accordion ID="MyAccordion" runat="server" RequireOpenedPane="false" HeaderCssClass="accordionHeader" ContentCssClass="accordionContent" FadeTransitions="true" FramesPerSecond="80" TransitionDuration="250" AutoSize="None"> </cc1:Accordion>
//This class has to be placed in App_Code: using System; using System.Drawing; using System.Windows.Forms; using System.Threading; using System.IO; using System.Reflection; namespace WebsiteThumbnail { public class WebsiteThumbnailImageGenerator { public static Bitmap GetWebSiteThumbnail(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight) { WebsiteThumbnailImage thumbnailGenerator = new WebsiteThumbnailImage(Url, BrowserWidth, BrowserHeight, ThumbnailWidth, ThumbnailHeight); return thumbnailGenerator.GenerateWebSiteThumbnailImage(); } private class WebsiteThumbnailImage { public WebsiteThumbnailImage(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight) { this.m_Url = Url; this.m_BrowserWidth = BrowserWidth; this.m_BrowserHeight = BrowserHeight; this.m_ThumbnailHeight = ThumbnailHeight; this.m_ThumbnailWidth = ThumbnailWidth; } private string m_Url = null; public string Url { get { return m_Url; } set { m_Url = value; } } private Bitmap m_Bitmap = null; public Bitmap ThumbnailImage { get { return m_Bitmap; } } private int m_ThumbnailWidth; public int ThumbnailWidth { get { return m_ThumbnailWidth; } set { m_ThumbnailWidth = value; } } private int m_ThumbnailHeight; public int ThumbnailHeight { get { return m_ThumbnailHeight; } set { m_ThumbnailHeight = value; } } private int m_BrowserWidth; public int BrowserWidth { get { return m_BrowserWidth; } set { m_BrowserWidth = value; } } private int m_BrowserHeight; public int BrowserHeight { get { return m_BrowserHeight; } set { m_BrowserHeight = value; } } public Bitmap GenerateWebSiteThumbnailImage() { Thread m_thread = new Thread(new ThreadStart(_GenerateWebSiteThumbnailImage)); m_thread.SetApartmentState(ApartmentState.STA); m_thread.Start(); m_thread.Join(); return m_Bitmap; } private void _GenerateWebSiteThumbnailImage() { WebBrowser m_WebBrowser = new WebBrowser(); m_WebBrowser.ScrollBarsEnabled = false; m_WebBrowser.Navigate(m_Url); m_WebBrowser.DocumentCompleted = new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted); while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete) Application.DoEvents(); m_WebBrowser.Dispose(); } private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { WebBrowser m_WebBrowser = (WebBrowser)sender; m_WebBrowser.ClientSize = new Size(this.m_BrowserWidth, this.m_BrowserHeight); m_WebBrowser.ScrollBarsEnabled = false; m_Bitmap = new Bitmap(m_WebBrowser.Bounds.Width, m_WebBrowser.Bounds.Height); m_WebBrowser.BringToFront(); m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds); m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(m_ThumbnailWidth, m_ThumbnailHeight, null, IntPtr.Zero); } } } } //This class is showed how to use it: using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Drawing; namespace WebsiteThumbnail { public partial class WebsiteThumbnailImagePage : System.Web.UI.Page { protected void btnShowThumbnailImage_Click(object sender, EventArgs e) { string address = "http://" txtWebsiteAddress.Text; int width = Int32.Parse(txtWidth.Text); int height = Int32.Parse(txtHeight.Text); Bitmap bmp = WebsiteThumbnailImageGenerator.GetWebSiteThumbnail(address, 1024, 768, width, height); bmp.Save(Server.MapPath("~") "/thumbnail/thumbnail.jpg"); imgWebsiteThumbnailImage.ImageUrl = "~/thumbnail/thumbnail.jpg"; imgWebsiteThumbnailImage.Visible = true; } } } //download this code here: //http://simpa.dk/smr/Examples/asp.net/thumbnail.zip
<%@ Page language="c#" AutoEventWireup="true" %> <%@ Import NameSpace="System" %> <%@ Import NameSpace="System.Data" %> <script runat="server" language="C#"> void Page_Load(object sender, EventArgs e) { DataTable dt = new DataTable("Export"); dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("Amount", typeof(double)); dt.Columns.Add("Cost", typeof(double)); DataRow row = null; for (int i = 0; i < 30; i) { row = dt.NewRow(); row[0] = "Name" i; row[1] = i.ToString(); row[2] = (i*2.5).ToString(); dt.Rows.Add(row); } DataView dv = dt.DefaultView; dv.Sort = "Amount DESC"; Session["dataview"] = dv; } </script> <title>Export to XML/CSV</title> <a href="export.aspx?type=xml">Export dataview (XML)</a><br> <a href="export.aspx?type=csv">Export dataview (CSV)</a> Here is the code for export.aspx: <%@ Page language="c#" AutoEventWireup="true" %> <%@ Import NameSpace="System.IO" %> <%@ Import NameSpace="System" %> <%@ Import NameSpace="System.Data" %> <%@ Import NameSpace="System.Web" %> <%@ Import NameSpace="System.Text" %> <script runat="server" language="C#"> void Page_Load(object sender, EventArgs e) { string type = Request.QueryString["type"] == null ? string.Empty : Request.QueryString["type"].ToLower(); _Name = Request.QueryString["name"] == null ? "export" : Request.QueryString["name"].ToLower(); Response.Clear(); switch (type) { case "xml": ExportXML(); break; case "csv": ExportCSV(); break; default: Response.Write("Wrong export type"); break; } } private string _Name = "export"; #region XML private void ExportXML() { DataTable dt = this.CleanUpDataTable(Session["dataview"] as DataView); StringBuilder sb = new StringBuilder(); sb.Append("<" dt.TableName ">"); foreach (DataRow row in dt.Rows) { sb.Append("<item>"); for (int i = 0; i < dt.Columns.Count; i) { sb.Append("<" dt.Columns[i].ColumnName ">" row[i].ToString() "</" dt.Columns[i].ColumnName ">"); } sb.Append("</item>"); } sb.Append("</" dt.TableName ">"); Response.ClearHeaders(); Response.AppendHeader("Content-Disposition", "attachment; filename=" _Name ".xml"); Response.AppendHeader("Content-Length", sb.Length.ToString()); Response.ContentType = "text/csv"; Response.Write(sb.ToString()); Response.End(); } #endregion #region CSV private void ExportCSV() { DataTable dt = this.CleanUpDataTable(Session["dataview"] as DataView); StringBuilder sb = new StringBuilder(); foreach (DataColumn col in dt.Columns) { sb.Append(col.ColumnName ";"); } sb.Remove(sb.Length - 1, 1); sb.Append(Environment.NewLine); foreach (DataRow row in dt.Rows) { for (int i = 0; i < dt.Columns.Count; i) { sb.Append(row[i].ToString() ";"); } sb.Append(Environment.NewLine); } Response.ClearHeaders(); Response.AppendHeader("Content-Disposition", "attachment; filename=" _Name ".csv"); Response.AppendHeader("Content-Length", sb.Length.ToString()); Response.ContentType = "text/csv"; Response.Write(sb.ToString()); Response.End(); } #endregion private DataTable CleanUpDataTable(DataView dv) { DataTable dt = new DataTable(dv.Table.TableName); DataRow dtRow = null; for (int i = 0; i < dv.Table.Columns.Count; i) { dt.Columns.Add(dv.Table.Columns[i].ColumnName, dv.Table.Columns[i].DataType); bool isInt = dv.Table.Columns[i].DataType == typeof(double); foreach (DataRow row in dv.Table.Rows) { if (isInt) { if (row[i] is DBNull) row[i] = "0"; } } } foreach (DataRowView row in dv) { dtRow = dt.NewRow(); for (int i = 0; i < dv.Table.Columns.Count; i) { dtRow[i] = row[i].ToString(); } dt.Rows.Add(dtRow); } return dt; } </script>
Step 1. <script type="text/javascript" src="Scripts/jquery-1.8.3/jquery.min.js"></script> Step 2. <!--if all actions on the page are client side insert true else if you are using updatepanel and handling your controls that way use false...--> /*body onload="$(document).ready(function() { initSession(true); })"*/ Step 3. <!--<asp:ScriptManager runat="server" ID="ScriptManager1" EnablePageMethods="true" />--> Step 4. <script type="text/javascript"> var sess_pollInterval = 60000; var sess_expirationMinutes = parseInt('<%= Session.Timeout %>'); var sess_warningMinutes = 19; var sess_intervalID; var sess_lastActivity; function initSession(activePokeServer) { if (typeof activePokeServer) { setInterval("PokeServerPage()", 1000 * 60 * sess_warningMinutes); } else { sess_lastActivity = new Date(); sessSetInterval(); $(document).bind('keypress.session', function (ed, e) { sessKeyPressed(ed, e); }); } } function sessSetInterval() { sess_intervalID = setInterval('sessInterval()', sess_pollInterval); } function sessClearInterval() { clearInterval(sess_intervalID); } function sessKeyPressed(ed, e) { sess_lastActivity = new Date(); } function sessLogOut() { window.location.href = 'Default.aspx'; } function sessInterval() { var now = new Date(); //get milliseconds of differneces var diff = now - sess_lastActivity; //get minutes between differences var diffMins = (diff / 1000 / 60); if (diffMins >= sess_warningMinutes) { //warn before expiring //stop the timer sessClearInterval(); //prompt for attention //var active = confirm('Your session will expire in ' + //(sess_expirationMinutes - sess_warningMinutes) + //' minutes (as of ' + now.toTimeString() + '), //press OK to remain logged in ' + //'or press Cancel to log off. //\nIf you are logged off any changes will be lost.'); //if (active == true) { PokeServerPage(); now = new Date(); diff = now - sess_lastActivity; diffMins = (diff / 1000 / 60); if (diffMins > sess_expirationMinutes) { sessLogOut(); } else { initSession(); sessSetInterval(); sess_lastActivity = new Date(); } //} //else { // sessLogOut(); //} } } function PokeServerPage() { PageMethods.PokeServerPage(); } </script> Step 5. [WebMethod(EnableSession = true)] public static void PokeServerPage() { //=> Poke server page to keep session alive... } Step 6. Security considerations...
step 1. Firstly create facebook app you will need the app id and app secret and setup website URL, domain etc... step 2. create this class in App_Code folder: using System.Configuration; using System.Web; public class fbConnect { public fbConnect() { } public static bool isConnected() { return (SessionKey != null && UserID != -1); } public static string ApiKey { get { return ConfigurationManager.AppSettings["APIKey"]; } } public static string SecretKey { get { return ConfigurationManager.AppSettings["Secret"]; } } public static string SessionKey { get { return GetFacebookCookie("session_key"); } } public static int UserID { get { int userID = -1; int.TryParse(GetFacebookCookie("user"), out userID); return userID; } } private static string GetFacebookCookie(string cookieName) { string retString = null; string fullCookie = ApiKey + "_" + cookieName; if (HttpContext.Current.Request.Cookies[fullCookie] != null) retString = HttpContext.Current.Request.Cookies[fullCookie].Value; return retString; } } step 3. Create Default.aspx or Index.aspx on client side insert: <!-- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Facebook Integration Sample</title> <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script> </head> <body> <form id="form1" runat="server"> <div id="login"> facebook test application <br /> <asp:Panel ID="pnlLogin" runat="server"> <fb:login-button length="long" v="2" onlogin="window.location.reload()">Login with facebook</fb:login-button><br /> </asp:Panel><br /> <asp:label id="lblMessage" runat="server" text="Not authenticated. Click Button to authenticate"></asp:label> <br /><br /> <asp:Image ID="imgPic" runat="server" AlternateText="" Visible="false"/> </div> </form> <script type="text/javascript"> FB.init("appID", "fb_receiver.htm"); </script> </body> </html> --> Step 4. In Default.aspx.cs insert: using System; using System.Configuration; using System.Data; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using facebook; using facebook.web; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (fbConnect.isConnected()) // Check if this application is authenticated { API api = new API(); api.ApplicationKey = fbConnect.ApiKey; api.SessionKey = fbConnect.SessionKey; api.Secret = fbConnect.SecretKey; api.uid = fbConnect.UserID; // hide the facebook button pnlLogin.Visible = false; try // be careful using try catch because we always want to find the error... { //Get the data of the signed user. string fullName = api.users.getInfo().first_name.ToUpper() + " " + api.users.getInfo().last_name.ToUpper(); lblMessage.Text = "You are login as " + fullName + " ID: " + api.users.getInfo().uid; imgPic.ImageUrl = api.users.getInfo().pic_big; Response.Redirect("Menu.aspx"); } catch { pnlLogin.Visible = true; } } else { pnlLogin.Visible = true; } } } Step 5. Then you need to add Cross Domain Site: <!-- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Cross-Domain Receiver Page</title> </head> <body> <script src="http://static.ak.facebook.com/js/api_lib/v0.4/XdCommReceiver.debug.js" type="text/javascript"></script> </body> </html> --> Step 6. This is the last step here you need to add appID, appSecret and callbackUrl in web.config </configSections> <appSettings> <add key="APIKey" value="appID"/> <add key="Secret" value="appSecret"/> <add key="Callback" value="http://simpa.dk/FacebookLogin/"></add> </appSettings > <connectionStrings> Download the binaries here "http://simpa.dk/FacebookLogin/bin.zip" Happy Coding...!
step 1. Firstly create facebook app you will need the app id and app secret and setup website URL, domain etc... step 2. create this class in App_Code folder: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using System.Web; public class ConnectAuthentication { public ConnectAuthentication() { } public static bool isConnected() { return (SessionKey != null && UserID != -1); } public static string ApiKey { get { return ConfigurationManager.AppSettings["APIKey"]; } } public static string SecretKey { get { return ConfigurationManager.AppSettings["Secret"]; } } public static string SessionKey { get { return GetFacebookCookie("session_key"); } } public static int UserID { get { int userID = -1; int.TryParse(GetFacebookCookie("user"), out userID); return userID; } } private static string GetFacebookCookie(string cookieName) { string retString = null; string fullCookie = ApiKey + "_" + cookieName; if (HttpContext.Current.Request.Cookies[fullCookie] != null) retString = HttpContext.Current.Request.Cookies[fullCookie].Value; return retString; } } step 3. Create Default.aspx or Index.aspx on client side insert: <!-- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="facebooklogin3010_Default" %> <%@ Register Assembly="Facebook.Web" Namespace="Facebook.Web.FbmlControls" TagPrefix="cc1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml"> <head runat="server"> <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script> <title>Facebook API 3.0.1.0 Test</title> </head> <body> <form id="form1" runat="server"> <div> <fb:login-button v="2" length="long" onlogin="window.location.reload()">Connect via facebook</fb:login-button> <br /> <br /> Facebook Connect: <asp:Label ID="Label1" runat="server" Text="Not Connected"></asp:Label> <br /> <br /> <br /> <br /> <asp:Image ID="imgPic" runat="server" AlternateText="" /> <br /> <asp:Panel ID="Panel1" runat="server" Visible="false"> <asp:TextBox ID="TextBox1" runat="server" Width="160px"></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="Post on my wall!" OnClick="Button1_Click" /> <asp:Button ID="Button2" runat="server" Text="Allow Access" OnClick="Button2_Click" /> </asp:Panel> </div> </form> <script type="text/javascript"> FB.init('<%=apiKey %>', "xd_receiver.htm"); </script> </body> </html> --> Step 4. In Default.aspx.cs insert: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Facebook.Schema; using Facebook.Winforms.Components; using Facebook.Rest; public partial class facebooklogin3010_Default : System.Web.UI.Page { Facebook.Web.FbmlControls.PromptPermission prompter = new Facebook.Web.FbmlControls.PromptPermission(); protected string apiKey; protected void Page_Load(object sender, EventArgs e) { apiKey = ConnectAuthentication.ApiKey; if (ConnectAuthentication.isConnected()) { Facebook.Session.ConnectSession session = new Facebook.Session.ConnectSession(ConnectAuthentication.ApiKey, ConnectAuthentication.SecretKey); try // be careful using try catch because we always want to find the error... { session.UserId = ConnectAuthentication.UserID; Facebook.Rest.Api api = new Facebook.Rest.Api(session); //Display user data captured from the Facebook API. Facebook.Schema.user user = api.Users.GetInfo(); string fullName = user.first_name + " " + user.last_name; Panel1.Visible = true; Label1.Text = fullName + " ID: " + user.uid; imgPic.ImageUrl = user.pic_big.ToString(); } catch(Exception ex) { //Label1.Text = ex.Message; //return; //session.SessionExpires = true; //session.Logout(); //Response.Redirect("http://simpa.dk/facebooklogin3010/"); } } else { //Facebook Connect not authenticated, proceed as usual. } } protected void Button1_Click(object sender, EventArgs e) { if (ConnectAuthentication.isConnected()) { FacebookService fbService = new FacebookService(); attachment attach = new attachment(); attach.caption = "Check this out..."; attach.description = "Posting from my Facebook development App"; attach.href = "http://simpa.dk/facebooklogin3010"; attach.name = "Attach my web link via FacebookAPI"; attachment_media attach_media = new attachment_media(); attach_media.type = attachment_media_type.image; attachment_media_image image = new attachment_media_image(); image.type = attachment_media_type.image; image.href = "http://simpa.dk/"; image.src = "http://simpa.dk/default/item1.png"; List<attachment_media> attach_media_list = new List<attachment_media>(); attach_media_list.Add(image); attach.media = attach_media_list; attachment_property attach_prop = new attachment_property(); /* action links */ List<action_link> actionlink = new List<action_link>(); action_link al1 = new action_link(); al1.href = "http://simpa.dk/"; al1.text = "simpa"; actionlink.Add(al1); Facebook.Session.ConnectSession session = new Facebook.Session.ConnectSession(ConnectAuthentication.ApiKey, ConnectAuthentication.SecretKey); session.UserId = ConnectAuthentication.UserID; Facebook.Rest.Api api = new Facebook.Rest.Api(session); //Display user data captured from the Facebook API. string publishAccess = api.ExtendedPermissionUrl(Facebook.Schema.Enums.ExtendedPermissions.publish_stream); api.Stream.Publish(TextBox1.Text, attach, actionlink, fbService.uid.ToString(), 0); } else { //Facebook Connect not authenticated, proceed as usual. } } private static Uri GetExtendedPermissionUrl(Enums.ExtendedPermissions permission) { return new Uri(String.Format("http://www.facebook.com/authorize.php?api_key={0}&v=1.0&ext_perm={1}", ConnectAuthentication.ApiKey, permission)); } protected void Button2_Click(object sender, EventArgs e) { Enums.ExtendedPermissions perm; perm = Enums.ExtendedPermissions.publish_stream; Uri uri = GetExtendedPermissionUrl(perm); Response.Redirect(uri.ToString()); } } Step 5. Then you need to add Cross Domain Site: <!-- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <body> <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.js" type="text/javascript"></script> </body> </html> --> Step 6. This is the last step here you need to add appID, appSecret and callbackUrl in web.config <configuration> <appSettings> <add key="APIKey" value="appID"/> <add key="Secret" value="appSecret"/> </appSettings> <connectionStrings> You can test this at "http://simpa.dk/facebooklogin3010" download the binaries here "http://simpa.dk/facebooklogin3010/SDK_Binaries.zip" Happy Coding...!
protected void Page_Load(object sender, EventArgs e) { var extendedPermissions = ConfigurationManager.AppSettings["extendedPermissions"].Split(','); if (!FacebookWebContext.Current.IsAuthorized(extendedPermissions)) { // this sample actually does not make use of FormsAuthentication, // besides redirecting to the proper login url defined in web.config // this will also automatically add ReturnUrl. FormsAuthentication.RedirectToLoginPage(); } else { // checking IsPostBack may reduce the number of requests to Facebook server. if (!IsPostBack) { var fb = new FacebookWebClient(); dynamic me = fb.Get("me"); imgProfilePic.ImageUrl = string.Format("https://graph.facebook.com/{0}/picture", me.id); lblName.Text = me.name; lblFirstName.Text = me.first_name; lblLastName.Text = me.last_name; LabelID.Text = me.id; } } } protected void btnPostToWall_Click(object sender, EventArgs e) { var fb = new FacebookWebClient(); dynamic parameters = new ExpandoObject(); parameters.message = txtMessage.Text; try { dynamic id = fb.Post("me/feed", parameters); lblPostMessageResult.Text = "Message posted successfully"; txtMessage.Text = string.Empty; } catch (FacebookApiException ex) { lblPostMessageResult.Text = ex.Message; } } //you can download this example i section Projects
server side: public partial class _Default : System.Web.UI.Page { protected AccordionPane pane; protected SlideShowExtender sse; protected Button Btn_Next; protected Button Btn_Play; protected Button Btn_Previous; protected Label lblImageDescription; protected Image Image1; protected int i; protected void Page_Load(object sender, EventArgs e) { i = -1; //try //{ DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory.ToString() + "images/"); DirectoryInfo[] tempdi = di.GetDirectories(); foreach (DirectoryInfo dirinfo in tempdi) { i++; pane = new AccordionPane(); pane.HeaderContainer.Controls.Add(new LiteralControl(dirinfo.ToString())); sse = new SlideShowExtender(); Btn_Next = new Button(); Btn_Next.Width = 64; Btn_Next.Height = 26; Btn_Next.Text = "Next"; Btn_Next.ID = UniqueID + "1148"; Btn_Previous = new Button(); Btn_Previous.ID = UniqueID + "1185"; Btn_Previous.Width = 62; Btn_Previous.Height = 25; Btn_Previous.Text = "Previous"; Btn_Play = new Button(); Btn_Play.ID = UniqueID + "1152"; sse.AutoPlay = true; lblImageDescription = new Label(); lblImageDescription.ID = UniqueID + "1119"; sse.ImageDescriptionLabelID = UniqueID + "1119"; sse.Loop = true; sse.NextButtonID = UniqueID + "1148"; sse.PreviousButtonID = UniqueID + "1185"; sse.PlayButtonID = UniqueID + "1152"; sse.PlayButtonText = "Play"; //sse.SlideShowServicePath = "webs.asmx"; sse.SlideShowServiceMethod = "GetSlides1"; sse.ContextKey = i.ToString(); sse.StopButtonText = "Stop"; Image1 = new Image(); Image1.Height = 316; Image1.Width = 388; Image1.ID = UniqueID + "1164"; sse.TargetControlID = UniqueID + "1164"; pane.ContentContainer.Controls.Add(lblImageDescription); pane.ContentContainer.Controls.Add(Image1); pane.ContentContainer.Controls.Add(Btn_Previous); pane.ContentContainer.Controls.Add(Btn_Play); pane.ContentContainer.Controls.Add(Btn_Next); pane.ContentContainer.Controls.Add(sse); MyAccordion.Controls.Add(pane); } } } client side: <script runat="Server" type="text/C#"> [System.Web.Services.WebMethod] [System.Web.Script.Services.ScriptMethod] public static AjaxControlToolkit.Slide[] GetSlides1(string contextKey) { AjaxControlToolkit.Slide[] slides = null; int i = -1; int index = int.Parse(contextKey); System.IO.DirectoryInfo dir1234 = new System.IO.DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory.ToString() + "images/"); System.IO.DirectoryInfo[] tempdir = dir1234.GetDirectories(); System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory.ToString() + tempdir[index].Parent.Name + "/" + tempdir[index].Name + "/"); System.IO.FileInfo[] gFiles = dir.GetFiles("*.jpg"); slides = new AjaxControlToolkit.Slide[gFiles.Length]; int tempi; foreach (System.IO.FileInfo fi in gFiles) { i++; tempi = i + 1; slides[i] = new AjaxControlToolkit.Slide(tempdir[index].Parent.Name + "/" + tempdir[index].Name + "/" + fi.Name, "", "< " + tempi.ToString() + " of " + gFiles.Length + " > " + tempdir[index].Name + ": " + fi.ToString().Split('.')[0]); //2. parameter does not work because of error in the toolkit } return (slides); } </script> and place this where you want the accordions to appear on the page: <cc1:accordion id="MyAccordion" runat="server" requireopenedpane="false" headercssclass="accordionHeader" contentcssclass="accordionContent" fadetransitions="true" framespersecond="80" transitionduration="250" autosize="None"> </cc1:accordion>
protected void LinkButton1_Click(object sender, EventArgs e) { Label1.Text = ""; List<string> result = new List<string>(); StreamReader re; using (re = new StreamReader(AppDomain.CurrentDomain.BaseDirectory.ToString() + "filename.txt", new System.Text.UTF7Encoding())) { string input = null; while ((input = re.ReadLine()) != null) { result.Add(input); } re.Close(); } foreach (string s in result) //Do something here... Label1.Text += s; }
<Names> <Name> <FirstName>John</FirstName> <LastName>Smith</LastName> </Name> <Name> <FirstName>James</FirstName> <LastName>White</LastName> </Name> </Names> XmlDocument xml = new XmlDocument(); xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>", if this succeds then you know if it is valid xml or not XmlNodeList xnList = xml.SelectNodes("/Names/Name"); foreach (XmlNode xn in xnList) { string firstName = xn["FirstName"].InnerText; string lastName = xn["LastName"].InnerText; Console.WriteLine("Name: {0} {1}", firstName, lastName); }
MailMessage msgMail = new MailMessage(); msgMail.To = "yourmail@hotmail.com"; msgMail.From = mail.Text; msgMail.Subject = subject.Text; msgMail.BodyFormat = MailFormat.Text; //msgMail.Attachments.Add( //new MailAttachment(FileUpload1.ToString())); strBody = "Name: " + name.Text + " \n " + message.Text; msgMail.Body = strBody; SmtpMail.SmtpServer = "yoursmtpserver"; try { SmtpMail.Send(msgMail); } catch { this.MessageLabel.Text = "An error has occured on the mailserver, please try again after few seconds..."; }
//get all dates and sort List<DateTime> threadcreated = new List<DateTime>(); string splitstring = null; bool exists = false; DirectoryInfo dilist = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory.ToString() + dir); DirectoryInfo[] tempdirlist = dilist.GetDirectories(); foreach (DirectoryInfo dirinfo in tempdirlist) { if (dirinfo.ToString() != "css" && dirinfo.ToString() != "design" && dirinfo.ToString() != "imgs") { try { //////Open the XML doc System.Xml.XmlDocument myXmlDocument5latest = new System.Xml.XmlDocument(); myXmlDocument5latest.Load(AppDomain.CurrentDomain.BaseDirectory.ToString() + dirinfo.Parent + "/" + dirinfo.ToString() + "/year.xml"); System.Xml.XmlNode myXmlNode5latest = myXmlDocument5latest.SelectSingleNode("configuration / appSettings"); //////Create new XML element and populate its attributes foreach (XmlNode childNode in myXmlNode5latest) { if (childNode.Attributes["key"].Value == "YearKey") splitstring = childNode.Attributes["value"].Value; } splitstring = splitstring.Split('k')[1]; splitstring = splitstring.Split(':')[1]; DateTime MyDateTime = new DateTime(); MyDateTime = Convert.ToDateTime(splitstring); //MyDateTime = DateTime.ParseExact(splitstring, "dd-MM-yyyy HH:mm:ss", null); if (threadcreated.Count == 0) threadcreated.Add(MyDateTime); else { foreach (DateTime dtnomultiple in threadcreated) { if (MyDateTime.Equals(dtnomultiple)) { exists = true; break; } else { exists = false; break; } } if (!exists) { threadcreated.Add(MyDateTime); } } } catch { } } } threadcreated.Sort(); threadcreated.Reverse(); if (threadcreated.Count > 5) { for (int i = threadcreated.Count - 1; i < threadcreated.Count; i--) { threadcreated.RemoveAt(i); if (threadcreated.Count < 6) { break; } } } //getall dates and sort end int counter = 0; string month = null; string day = null; foreach (DateTime dt in threadcreated) { if (dt.Month < 10) month = "0" + dt.Month; else month = dt.Month.ToString(); if (dt.Day < 10) day = "0" + dt.Day; else day = dt.Day.ToString(); string dtstring = day + "/" + month + "/" + dt.Year; foreach (DirectoryInfo dirinfo2 in tempdirlist) { if (dirinfo2.ToString() != "css" && dirinfo2.ToString() != "design" && dirinfo2.ToString() != "imgs") { string splitstringcheck2 = null; //////Open the XML doc System.Xml.XmlDocument myXmlDocument5latest2 = new System.Xml.XmlDocument(); myXmlDocument5latest2.Load(AppDomain.CurrentDomain.BaseDirectory.ToString() + dirinfo2.Parent + "/" + dirinfo2.ToString() + "/year.xml"); System.Xml.XmlNode myXmlNode5latest2 = myXmlDocument5latest2.SelectSingleNode("configuration / appSettings"); //////Create new XML element and populate its attributes foreach (XmlNode childNode in myXmlNode5latest2) { if (childNode.Attributes["key"].Value == "YearKey") splitstringcheck2 = childNode.Attributes["value"].Value; } splitstringcheck2 = splitstringcheck2.Split('k')[1]; splitstringcheck2 = splitstringcheck2.Split(':')[1]; string[] s2 = splitstringcheck2.Split('-'); string comparestring2 = s2[0] + "/" + s2[1] + "/" + s2[2]; if (dtstring.Equals(comparestring2.Trim()) && counter < 5) { lbtn = new LinkButton(); lbtn.ID = dirinfo2.ToString(); lbtn.Text = dirinfo2.ToString() + "<br>"; lbtn.Click += new EventHandler(LinkButton_Click); PanelPopUp.Controls.Add(lbtn); counter++; //break; } } } }
Client side code: <!-- <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Service4.aspx.cs" Inherits="Services_Service4" title="Service4 Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <link href="../_scripts/uploadify.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="../_scripts/jquery-1.4.4.min.js"></script> <script type="text/javascript" src="../_scripts/swfobject.js"></script> <script type="text/javascript" src="../_scripts/jquery.uploadify.v2.1.4.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#fuFiles').uploadify({ 'uploader': '../_scripts/uploadify.swf', 'script': 'Administration/Service4.aspx', 'cancelImg': '../_scripts/cancel.png', 'auto': 'true', 'multi': 'true', 'buttonText': 'Browse...', 'queueSizeLimit': 6, 'simUploadLimit': 4 }); }); </script> <script type="text/javascript"> function addFileUploadBox() { if (!document.getElementById || !document.createElement) return false; var uploadArea = document.getElementById("upload-area"); if (!uploadArea) return; var newLine = document.createElement("br"); uploadArea.appendChild(newLine); var newUploadBox = document.createElement("input"); // Set up the new input for file uploads newUploadBox.type = "file"; newUploadBox.size = "60"; // The new box needs a name and an ID if (!addFileUploadBox.lastAssignedId) addFileUploadBox.lastAssignedId = 100; newUploadBox.setAttribute("id", "dynamic" + addFileUploadBox.lastAssignedId); newUploadBox.setAttribute("name", "dynamic:" + addFileUploadBox.lastAssignedId); uploadArea.appendChild(newUploadBox); addFileUploadBox.lastAssignedId++; } </script> <div id="fuFiles"></div> <br /> <br /> <br /> <br /> <p id="upload-area"> <input id="File1" type="file" runat="server" size="60" /> </p> <input id="AddFile" type="button" value="Add file" onclick="addFileUploadBox()" /> <p><asp:Button ID="btnSubmit" runat="server" Text="Upload Now" OnClick="btnSubmit_Click" /></p> <span id="Span1" runat="server" /> <%-- <br /> <br />--%> <%--<asp:FileUpLoad id="FileUpLoad1" runat="server" />--%> <br /> <%-- <asp:Button id="UploadBtn" Text="Upload File" OnClick="UploadBtn_Click" runat="server" Width="105px" />--%> <br /> <asp:Label id="Label1" runat="server" /><br /><br /> <asp:Button ID="Button1" runat="server" Text="Refresh file list" OnClick="Button1_Click"/> <br /> <asp:GridView ID="GridView1" runat="server" onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" AllowPaging="true" onselectedindexchanging="GridView1_SelectedIndexChanging"> <Columns> <asp:CommandField ShowEditButton="True" InsertVisible="False" EditText="Download"/> <asp:CommandField ShowDeleteButton="True" InsertVisible="False" /> <asp:CommandField ShowSelectButton="True" InsertVisible="False" SelectText="Vis"/> </Columns> </asp:GridView> </asp:Content> --> <!-- Server side code: using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Net; using System.IO; using System.Text; using System.Linq; using System.Xml.Linq; public partial class Services_Service4 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //try //{ // HttpPostedFile uploads = Request.Files["FileData"]; // string file = System.IO.Path.GetFileName(uploads.FileName); // string localpath = System.IO.Path.GetFullPath(uploads.FileName); // try // { // uploads.SaveAs("D:\\UploadedUserFiles\\" + file); // } // catch // { // } //} //catch { } Button1_Click(sender, e); } private DataTable CreateTable() { try { DataTable table = new DataTable(); // Declare DataColumn and DataRow variables. DataColumn column; // Create new DataColumn, set DataType, ColumnName // and add to DataTable. column = new DataColumn(); column.DataType = System.Type.GetType("System.String"); column.ColumnName = "Files:"; table.Columns.Add(column); // Create second column. //column = new DataColumn(); //column.DataType = Type.GetType("System.String"); //column.ColumnName = "Time"; //table.Columns.Add(column); //column = new DataColumn(); //column.DataType = System.Type.GetType("System.String"); //column.ColumnName = "Source"; //table.Columns.Add(column); //column = new DataColumn(); //column.DataType = System.Type.GetType("System.String"); //column.ColumnName = "Description"; //table.Columns.Add(column); return table; } catch (Exception ex) { throw new Exception(ex.Message); } } protected void Button1_Click(object sender, EventArgs e) { try { Label1.Text = ""; FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://"); request.Credentials = new NetworkCredential("user", "pass"); request.Method = WebRequestMethods.Ftp.ListDirectory; StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream(), new System.Text.UTF7Encoding()); string fileName = streamReader.ReadToEnd(); GridView1.AutoGenerateColumns = true; DataTable table = CreateTable(); DataRow row; foreach (string s in fileName.Split(new string[] { "\r\n" }, StringSplitOptions.None)) { //BoundField bf = new BoundField(); //bf.DataField = s; //bf.HeaderText = "Files:"; ////Console.Writeline(fileName); ////fileName = streamReader.ReadLine(); //GridView1.Columns.Add(bf); row = table.NewRow(); row["Files:"] = s; if (row.ItemArray[0] != null && row.ItemArray[0].ToString() != "") table.Rows.Add(row); } request = null; streamReader = null; //streamReader.Dispose(); GridView1.DataSource = table; GridView1.DataBind(); } catch (Exception xp) { Label1.Text = xp.Message; } } protected void btnSubmit_Click(object sender, EventArgs e) { HttpFileCollection uploads = HttpContext.Current.Request.Files; for (int i = 0; i < uploads.Count; i++) { HttpPostedFile upload = uploads[i];//file; //if (upload.ContentLength == 0) // continue; string c = null; string localpath = null; try { c = System.IO.Path.GetFileName(upload.FileName); localpath = System.IO.Path.GetFullPath(upload.FileName); } catch { } try { try { Label1.Text = ""; string fileName = c; string localPath = localpath; FtpWebRequest requestFTPUploader = (FtpWebRequest)WebRequest.Create("ftp://" + fileName); requestFTPUploader.Credentials = new NetworkCredential("user", "pass"); requestFTPUploader.Method = WebRequestMethods.Ftp.UploadFile; FileInfo fileInfo = new FileInfo(localPath); FileStream fileStream = fileInfo.OpenRead(); int bufferLength = 2048; byte[] buffer = new byte[bufferLength]; Stream uploadStream = requestFTPUploader.GetRequestStream(); int contentLength = fileStream.Read(buffer, 0, bufferLength); while (contentLength != 0) { uploadStream.Write(buffer, 0, contentLength); contentLength = fileStream.Read(buffer, 0, bufferLength); } uploadStream.Close(); fileStream.Close(); requestFTPUploader = null; Session["files"] += c + ", "; } catch (Exception Exp) { Span1.InnerHtml = "Upload(s) FAILED."; } } catch (Exception xp) { Label1.Text = xp.Message; } } try { string s = Session["files"].ToString(); Label1.Text = "File(s) Uploaded: " + s.Substring(0, s.Length - 2); } catch { } } //protected void UploadBtn_Click(object sender, EventArgs e) //{ // try // { // Label1.Text = ""; // if (FileUpLoad1.FileName != string.Empty) // { // string fileName = FileUpLoad1.FileName; // string localPath = FileUpLoad1.PostedFile.FileName; // FtpWebRequest requestFTPUploader = (FtpWebRequest)WebRequest.Create("ftp://" + fileName); // requestFTPUploader.Credentials = new NetworkCredential("user", "pass"); // requestFTPUploader.Method = WebRequestMethods.Ftp.UploadFile; // FileInfo fileInfo = new FileInfo(localPath); // FileStream fileStream = fileInfo.OpenRead(); // int bufferLength = 2048; // byte[] buffer = new byte[bufferLength]; // Stream uploadStream = requestFTPUploader.GetRequestStream(); // int contentLength = fileStream.Read(buffer, 0, bufferLength); // while (contentLength != 0) // { // uploadStream.Write(buffer, 0, contentLength); // contentLength = fileStream.Read(buffer, 0, bufferLength); // } // uploadStream.Close(); // fileStream.Close(); // requestFTPUploader = null; // Label1.Text = "File Uploaded: " + FileUpLoad1.FileName; // } // else // { // Label1.Text = "No File Uploaded."; // } // } // catch (Exception xp) { Label1.Text = xp.Message; } //} protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) {//delete string fileName = Server.HtmlDecode(GridView1.Rows[e.RowIndex].Cells[3].Text); FtpWebRequest requestFileDelete = (FtpWebRequest)WebRequest.Create("ftp://" + fileName); requestFileDelete.Credentials = new NetworkCredential("user", "pass"); requestFileDelete.Method = WebRequestMethods.Ftp.DeleteFile; FtpWebResponse responseFileDelete = (FtpWebResponse)requestFileDelete.GetResponse(); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) {//download string fileName = Server.HtmlDecode(GridView1.Rows[e.NewEditIndex].Cells[3].Text); FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create("ftp://" + fileName); requestFileDownload.Credentials = new NetworkCredential("user", "pass"); requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile; int i = 0; FtpWebResponse responseFileDownload = null; while (i < 1) { try { responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse(); i = 1; } catch { responseFileDownload = null; Response.Write("<script>alert('der var fejl ved forbindelsen prøv lige igen...')</script>"); break; } finally { } } if (i > 0) { Stream responseStream = responseFileDownload.GetResponseStream(); Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); int Length = 2048; Byte[] buffer = new Byte[Length]; int bytesRead = responseStream.Read(buffer, 0, Length); returnContentType(fileName); //Response.AddHeader("Content-transfer-encoding", "binary"); Response.ContentEncoding = System.Text.UTF8Encoding.UTF7; Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName); // Response.AddHeader("Content-Type", "Application/octet-stream"); //Response.AddHeader("Content-Length", Length.ToString()); //FileStream writeStream = new FileStream(localPath + fileName, FileMode.Create); //int Length = 2048; //Byte[] buffer = new Byte[Length]; //int bytesRead = responseStream.Read(buffer, 0, Length); while (bytesRead > 0) { //writeStream.Write(buffer, 0, bytesRead); Response.OutputStream.Write(buffer, 0, bytesRead); //Response.BinaryWrite(buffer); bytesRead = responseStream.Read(buffer, 0, Length); } Response.Flush(); Response.End(); Response.OutputStream.Flush(); responseStream.Close(); responseStream.Flush(); //writeStream.Close(); requestFileDownload = null; responseFileDownload = null; } } private void returnContentType(string fileName) { switch (Path.GetExtension(fileName).Split('.')[1])//(fileName.Split('.')[1])//that is dangerous to use, use .net implemented method to return file type { case "swf": Response.ContentType = "application/x-shockwave-flash"; break; case "png": Response.ContentType = "image/png"; break; case "mp4": Response.ContentType = "video/mp4"; break; case "mov": Response.ContentType = "video/quicktime"; break; case "wmv": case "avi": Response.ContentType = "video/x-ms-wmv"; break; case "htm": case "html": case "log": Response.ContentType = "text/HTML"; break; case "txt": Response.ContentType = "text/plain"; break; case "doc": case "docx": Response.ContentType = "application/ms-word"; break; case "tiff": case "tif": Response.ContentType = "image/tiff"; break; case "asf": Response.ContentType = "video/x-ms-asf"; break; case "asx": Response.ContentType = "video/x-ms-asf"; break; case "bin": Response.ContentType = "application/octet-stream"; break; case "zip": Response.ContentType = "application/zip"; break; case "xls": case "csv": Response.ContentType = "application/vnd.ms-excel"; break; case "gif": Response.ContentType = "image/gif"; break; case "jpg": case "jpeg": Response.ContentType = "image/jpeg"; break; case "pic": case "pict": Response.ContentType = "image/pict"; break; case "bmp": Response.ContentType = "image/bmp"; break; case "wav": Response.ContentType = "audio/wav"; break; case "mp3": Response.ContentType = "audio/mpeg3"; break; case "mpg": case "mpeg": Response.ContentType = "video/mpeg"; break; case "rtf": Response.ContentType = "application/rtf"; break; case "asp": Response.ContentType = "text/asp"; break; case "pdf": Response.ContentType = "application/pdf"; break; case "fdf": Response.ContentType = "application/vnd.fdf"; break; case "ppt": case "pptx": Response.ContentType = "application/mspowerpoint"; break; case "dwg": Response.ContentType = "image/vnd.dwg"; break; case "msg": Response.ContentType = "application/msoutlook"; break; case "xml": case "sdxl": Response.ContentType = "application/xml"; break; case "xdp": Response.ContentType = "application/vnd.adobe.xdp+xml"; break; default: Response.ContentType = "application/octet-stream"; break; } } protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e) {//vis string fileName = Server.HtmlDecode(GridView1.Rows[e.NewSelectedIndex].Cells[3].Text); FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create("ftp://" + fileName); requestFileDownload.Credentials = new NetworkCredential("user", "pass"); requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile; int i = 0; FtpWebResponse responseFileDownload = null; while (i < 1) { try { responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse(); i = 1; } catch { responseFileDownload = null; Response.Write("<script>alert('der var fejl ved forbindelsen prøv lige igen...')</script>"); break; } finally { } } if (i > 0) { Stream responseStream = responseFileDownload.GetResponseStream(); Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); int Length = 2048; Byte[] buffer = new Byte[Length]; int bytesRead = responseStream.Read(buffer, 0, Length); returnContentType(fileName); //Response.AddHeader("Content-transfer-encoding", "binary"); Response.ContentEncoding = System.Text.UTF8Encoding.UTF7; Response.AddHeader("Content-Disposition", "filename=" + fileName); //Response.AddHeader("Content-Length", Length.ToString()); //FileStream writeStream = new FileStream(localPath + fileName, FileMode.Create); //int Length = 2048; //Byte[] buffer = new Byte[Length]; //int bytesRead = responseStream.Read(buffer, 0, Length); while (bytesRead > 0) { //writeStream.Write(buffer, 0, bytesRead); Response.OutputStream.Write(buffer, 0, bytesRead); //Response.BinaryWrite(buffer); bytesRead = responseStream.Read(buffer, 0, Length); } Response.Flush(); Response.End(); Response.OutputStream.Flush(); responseStream.Close(); responseStream.Flush(); //writeStream.Close(); requestFileDownload = null; responseFileDownload = null; } } } -->
//In body of your page add this: //body onkeypress="keypress(event)" then add this script: <script type="text/javascript"> function keypress(event) { var key = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode; if (key == 13) { bt = document.getElementById('<%= Button3.ClientID %>'); bt.click(); } else if (key == 32) { bt = document.getElementById('<%= Button4.ClientID %>'); bt.click(); } } </script>