I can't get my static class working with a Generic List - asp.net

I have a static class that needs to pass a generic List of strings to a function using an integer as a index to the List in the class. The problem is the static class doesn't have a List collect and I don't have a proper index to access the class in the function it is passed to. The class, the calling code, and the receiving function are below.
My Class:
public class QueryContainer
{
public static QueryContainer Instance = new QueryContainer();
private int _id;
private string _query = "";
private int _searchID;
public QueryContainer() { }
public string Query
{
get
{
if (Instance != null)
return Instance._query;
else
return "";
}
set { _query = value; _id =+ 1; }
}
public int ID { get { return _id; } }
public int SearchID
{
set { _searchID = value; }
get { return _searchID; }
}
}
The calling code:
public int GetAccountSortByAccountCode(int account)
{
int Id = 0;
QueryContainer.Instance.Query = "SELECT ac_sort_order FROM lkup_account_codes where ac_code = " + account.ToString();
return Convert.ToInt32(ExecuteScaler(Id));
}
The function that the static class is passed to:
public int GetAccountSortByAccountCode(int account)
{
int Id = 0;
QueryContainer.Instance.Query = "SELECT ac_sort_order FROM lkup_account_codes where ac_code = " + account.ToString();
return Convert.ToInt32(ExecuteScaler(Id));
}
The Function
protected Object ExecuteScaler(int ID)
{
object returnValue = null;
if (!_iserror)
{
if (_trace)
{ DoTrace("TAMIS.Data.Loader.ExecuteScalar", QueryContainer.Instance.Query); }
if (_connection == null || _connection.State == ConnectionState.Closed)
{
OpenConnection();
}
DbCommand command = _provider.CreateCommand();
command.Connection = _connection;
{
command.CommandText = QueryContainer.Instance.Query;
command.CommandType = CommandType.Text;
if (_useTransaction) { command.Transaction = _transaction; }
try
{
returnValue = command.ExecuteScalar();
}
catch (Exception ex)
{
if (ex is EntryPointNotFoundException)
throw ex;
//if (_useTransaction == true)
//_transaction.Rollback();
RollBack();
LogBLL bll = new LogBLL();
bll.WriteErrorLog(ex);
_iserror = true;
}
finally
{
if ((!KeepAlive && _connection.State == ConnectionState.Open) || _iserror == true)
{
CloseConnection();
}
}
}
}
else
{
returnValue = -1;
}
return returnValue;
}

You are using QueryContainer as a Singleton.
In ASP.Net, you receives multiple requests from different users. It is not a good way to construct dynamic query.
Basically, what you are doing is all requests will use same QueryContainer instance. I don't think it is what you want.
The bottom line is do not use static in your scenario.

Related

C# console doesn't print exception message

I have a ASP.NET project and in some part of it I call a business rule to test the form:
[HttpPost]
public ActionResult InsertProduct(Product Product)
{
try
{
InsertProductBLL ProductInsertion = new InsertProductBLL (Product.Value, Product.Description);
ProductInsertion.IsValid();
return PartialView("Success");
}
catch (Exception e)
{
Console.Write(e.Message);
return PartialView("Fail");
}
}
On the BLL, I have this:
public void IsValid()
{
if (Value> 10) ; //I just want the else section
else
{
Exception e = new Exception("Insert a bigger value");
throw e;
}
}
However, the console only prints that the exception has been thrown, but not the message that I asked for. Is there any syntax mistake or something that I just messed up?
You can do something like this,
Create Result Object which can be used to transmit data between layers.
public class Result
{
public HasResult { get; set; }
public ErrorMessage { get; set;}
public SuccessMessage { get; set;}
}
Transfer as a Result Object to the calling layer (here in your case Controller) after all your business validations.
public Result IsValid(int Value)
{
var result = new Result();
result.HasResult = Value > 10;//set this after all your business rules
if(HasResult)
{
result.SuccessMessage = "Success";
}
else
{
result.ErrorMessage = "Insert a bigger value";
}
return result;
}
In Controller
[HttpPost]
public ActionResult InsertProduct(Product Product)
{
var returnMessage = "";
try
{
InsertProductBLL ProductInsertion = new InsertProductBLL (Product.Value, Product.Description);
var result = ProductInsertion.IsValid(Product.Value);
returnMessage = result.HasResult
? result.SuccessMessage
: result.ErrorMessage;
}
catch (Exception e)
{
Console.Write(e.Message);
returnMessage = "Fail";
}
return PartialView(returnMessage);
}

receive mail using pop3 asp.net of hotmail

I am using POP3 Code for the receiving mail from mail Server It runs good on GMail and yahoo but when i am trying to connect with hotmail o ma getting error over
string response = SendCommand("STAT");
"-ERR command not expected now\r\n"
I am attaching mail code please review it and suggest me the possible solution.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
namespace CallScreen24x7.BAL
{
public class Pop3Client : IDisposable
{
//string _host,_email,_pass;
//int port;
// string _host = ConfigurationSettings.AppSettings["host"];
public string Host { get; protected set; }
public int Port { get; protected set; }
public string Email { get; protected set; }
public string Password { get; protected set; }
public bool IsSecure { get; protected set; }
public TcpClient Client { get; protected set; }
public Stream ClientStream { get; protected set; }
public StreamWriter Writer { get; protected set; }
public StreamReader Reader { get; protected set; }
private bool disposed = false;
//public Pop3Client(string host, int port, string email, string password) : this("mail.ansitdev.com", 110, "dev#ansitdev.com", "P#ssword123", false) { }
public Pop3Client(string host, int port, string email, string password, bool secure)
{
try
{
Host = host;// ConfigurationSettings.AppSettings["host"];// "mail.ansitdev.com";
Port = port;
Email = email;// "dev#ansitdev.com";
Password = password;// ;
IsSecure = true;
}
catch (Exception ex)
{ }
}
public void Connect()
{
try
{
if (Client == null)
Client = new TcpClient();
if (!Client.Connected)
Client.Connect(Host, Port);
if (IsSecure)
{
SslStream secureStream = new SslStream(Client.GetStream());
secureStream.AuthenticateAsClient(Host);
ClientStream = secureStream;
secureStream = null;
}
else
ClientStream = Client.GetStream();
Writer = new StreamWriter(ClientStream);
Reader = new StreamReader(ClientStream);
ReadLine();
Login();
}
catch(Exception ex)
{}
}
public int GetEmailCount()
{
int count = 0;
string response = SendCommand("STAT");
if (IsResponseOk(response))
{
string[] arr = response.Substring(4).Split(' ');
count = Convert.ToInt32(arr[0]);
}
else
count = -1;
return count;
}
public Email FetchEmail(int emailId)
{
if (IsResponseOk(SendCommand("TOP " + emailId + " 0")))
return new Email(ReadLines());
else
return null;
}
public List<Email> FetchEmailList(int start, int count)
{
List<Email> emails = new List<Email>(count);
for (int i = start; i >=(start-count)+1; i--)
{
if (i >= 0)
{
Email email = FetchEmail(i);
if (email != null)
emails.Add(email);
}
}
return emails;
}
public List<MessagePart> FetchMessageParts(int emailId)
{
if (IsResponseOk(SendCommand("RETR " + emailId)))
return Util.ParseMessageParts(ReadLines());
return null;
}
public void Close()
{
try
{
if (Client != null)
{
if (Client.Connected)
Logout();
Client.Close();
Client = null;
}
if (ClientStream != null)
{
ClientStream.Close();
ClientStream = null;
}
if (Writer != null)
{
Writer.Close();
Writer = null;
}
if (Reader != null)
{
Reader.Close();
Reader = null;
}
disposed = true;
}
catch (Exception ex)
{ }
}
public void Dispose()
{
try
{
if (!disposed)
Close();
}
catch (Exception ex)
{ }
}
protected void Login()
{
try
{
if (!IsResponseOk(SendCommand("USER " + Email)) || !IsResponseOk(SendCommand("PASS " + Password))) { }
// throw new Exception("User/password not accepted");
}
catch (Exception ex)
{ }
}
protected void Logout()
{
SendCommand("RSET");
}
protected string SendCommand(string cmdtext)
{
try
{
Writer.WriteLine(cmdtext);
Writer.Flush();
return ReadLine();
}
catch (Exception ex) { return null; }
}
protected string ReadLine()
{
return Reader.ReadLine() + "\r\n";
}
protected string ReadLines()
{
StringBuilder b = new StringBuilder();
while (true)
{
string temp = ReadLine();
if (temp == ".\r\n" || temp.IndexOf("-ERR") != -1)
break;
b.Append(temp);
}
return b.ToString();
}
protected static bool IsResponseOk(string response)
{
if (response.StartsWith("+OK"))
return true;
if (response.StartsWith("-ERR"))
return false;
return true;
// throw new Exception("Cannot understand server response: " + response);
}
}
public class Email
{
public NameValueCollection Headers { get; protected set; }
public string ContentType { get; protected set; }
public DateTime UtcDateTime { get; protected set; }
public string From { get; protected set; }
public string To { get; protected set; }
public string Subject { get; protected set; }
public Email(string emailText)
{
Headers = Util.ParseHeaders(emailText);
ContentType = Headers["Content-Type"];
From = Headers["From"];
To = Headers["To"];
Subject = Headers["Subject"];
if (Headers["Date"] != null)
try
{
UtcDateTime = Util.ConvertStrToUtcDateTime(Headers["Date"]);
}
catch (FormatException)
{
UtcDateTime = DateTime.MinValue;
}
else
UtcDateTime = DateTime.MinValue;
}
}
public class MessagePart
{
public NameValueCollection Headers { get; protected set; }
public string ContentType { get; protected set; }
public string MessageText { get; protected set; }
public MessagePart(NameValueCollection headers, string messageText)
{
Headers = headers;
ContentType = Headers["Content-Type"];
MessageText = messageText;
}
}
public class Util
{
protected static Regex BoundaryRegex = new Regex("Content-Type: multipart(?:/\\S+;)" + "\\s+[^\r\n]*boundary=\"?(?<boundary>" + "[^\"\r\n]+)\"?\r\n", RegexOptions.IgnoreCase | RegexOptions.Compiled);
protected static Regex UtcDateTimeRegex = new Regex(#"^(?:\w+,\s+)?(?<day>\d+)\s+(?<month>\w+)\s+(?<year>\d+)\s+(?<hour>\d{1,2})" + #":(?<minute>\d{1,2}):(?<second>\d{1,2})\s+(?<offsetsign>\-|\+)(?<offsethours>" + #"\d{2,2})(?<offsetminutes>\d{2,2})(?:.*)$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
public static NameValueCollection ParseHeaders(string headerText)
{
NameValueCollection headers = new NameValueCollection();
StringReader reader = new StringReader(headerText);
string line;
string headerName = null, headerValue;
int colonIndx;
while ((line = reader.ReadLine()) != null)
{
if (line == "")
break;
if (Char.IsLetterOrDigit(line[0]) && (colonIndx = line.IndexOf(':')) != -1)
{
headerName = line.Substring(0, colonIndx);
headerValue = line.Substring(colonIndx + 1).Trim();
headers.Add(headerName, headerValue);
}
else if (headerName != null)
headers[headerName] += " " + line.Trim();
else
throw new FormatException("Could not parse headers");
}
return headers;
}
public static List<MessagePart> ParseMessageParts(string emailText)
{
List<MessagePart> messageParts = new List<MessagePart>();
int newLinesIndx = emailText.IndexOf("\r\n\r\n");
Match m = BoundaryRegex.Match(emailText);
if (m.Index < emailText.IndexOf("\r\n\r\n") && m.Success)
{
string boundary = m.Groups["boundary"].Value;
string startingBoundary = "\r\n--" + boundary;
int startingBoundaryIndx = -1;
while (true)
{
if (startingBoundaryIndx == -1)
startingBoundaryIndx = emailText.IndexOf(startingBoundary);
if (startingBoundaryIndx != -1)
{
int nextBoundaryIndx = emailText.IndexOf(startingBoundary, startingBoundaryIndx + startingBoundary.Length);
if (nextBoundaryIndx != -1 && nextBoundaryIndx != startingBoundaryIndx)
{
string multipartMsg = emailText.Substring(startingBoundaryIndx + startingBoundary.Length, (nextBoundaryIndx - startingBoundaryIndx - startingBoundary.Length));
int headersIndx = multipartMsg.IndexOf("\r\n\r\n");
if (headersIndx == -1)
throw new FormatException("Incompatible multipart message format");
string bodyText = multipartMsg.Substring(headersIndx).Trim();
NameValueCollection headers = Util.ParseHeaders(multipartMsg.Trim());
messageParts.Add(new MessagePart(headers, bodyText));
}
else
break;
startingBoundaryIndx = nextBoundaryIndx;
}
else
break;
}
if (newLinesIndx != -1)
{
string emailBodyText = emailText.Substring(newLinesIndx + 1);
}
}
else
{
int headersIndx = emailText.IndexOf("\r\n\r\n");
if (headersIndx == -1)
throw new FormatException("Incompatible multipart message format");
string bodyText = emailText.Substring(headersIndx).Trim();
NameValueCollection headers = Util.ParseHeaders(emailText);
messageParts.Add(new MessagePart(headers, bodyText));
}
return messageParts;
}
public static DateTime ConvertStrToUtcDateTime(string str)
{
Match m = UtcDateTimeRegex.Match(str);
int day, month, year, hour, min, sec;
if (m.Success)
{
day = Convert.ToInt32(m.Groups["day"].Value);
year = Convert.ToInt32(m.Groups["year"].Value);
hour = Convert.ToInt32(m.Groups["hour"].Value);
min = Convert.ToInt32(m.Groups["minute"].Value);
sec = Convert.ToInt32(m.Groups["second"].Value);
switch (m.Groups["month"].Value)
{
case "Jan":
month = 1;
break;
case "Feb":
month = 2;
break;
case "Mar":
month = 3;
break;
case "Apr":
month = 4;
break;
case "May":
month = 5;
break;
case "Jun":
month = 6;
break;
case "Jul":
month = 7;
break;
case "Aug":
month = 8;
break;
case "Sep":
month = 9;
break;
case "Oct":
month = 10;
break;
case "Nov":
month = 11;
break;
case "Dec":
month = 12;
break;
default:
throw new FormatException("Unknown month.");
}
DateTime dt = new DateTime(year, month, day, hour, min, sec);
DateTime kt = dt.AddHours(-offsetHours);
kt = kt.AddMinutes(-offsetMinutes);
return kt;
}
throw new FormatException("Incompatible date/time string format");
}
}
}
and
int page = 1;
if (Request.QueryString["page"] == null)
{
Response.Redirect("DashBoard.aspx?page=1");
Response.Flush();
Response.End();
}
else
page = Convert.ToInt32(Request.QueryString["page"]);
try
{
Email = ConfigurationSettings.AppSettings["email"].ToString();
Password = ConfigurationSettings.AppSettings["pass"].ToString();
}
catch (Exception ex)
{
Response.Redirect("DashBoard.aspx");
objentityException.ExceptionDescription = ex.Message + " " + ex.StackTrace; ;
objentityException.MethodName = "Page_Load";
objentityException.CreatedBy = Session["UserName"].ToString();
objException.InsertException(objentityException);
}
int totalEmails;
List<Email> emails;
string emailAddress;
using (Pop3Client client = new Pop3Client(Host, Port, Email, Password, false))
{
emailAddress = client.Email;
client.Connect();
totalEmails = client.GetEmailCount();
emails = client.FetchEmailList((totalEmails - ((page - 1) * 5)), NoOfEmailsPerPage);
}
int totalPages;
int mod = totalEmails % NoOfEmailsPerPage;
if (mod == 0)
totalPages = totalEmails / NoOfEmailsPerPage;
else
totalPages = ((totalEmails - mod) / NoOfEmailsPerPage) + 1;
for (int i = 0; i < emails.Count; i++)
{
AdminTransaction AT = new AdminTransaction();
DAL.Emails objEmail = new DAL.Emails();
Email email = emails[i];
int emailId = ((totalEmails - ((page - 1) * 5) - i));
TableCell noCell = new TableCell();
noCell.CssClass = "emails-table-cell";
noCell.Text = Convert.ToString(emailId);
objEmail.EmailNo = emailId;
TableCell fromCell = new TableCell();
fromCell.Text = email.From;
TableCell subjectCell = new TableCell();
subjectCell.Style["width"] = "300px";
subjectCell.Text = String.Format(DisplayEmailLink, emailId, page, email.Subject);
TableCell dateCell = new TableCell();
if (email.UtcDateTime != DateTime.MinValue)
dateCell.Text = email.UtcDateTime.ToString();
int x = AT.AddEmail(objEmail);
DataSet ds = AT.GetMailStatus(emailId);
if (ds.Tables[0].Rows.Count > 0)
{
// subjectCell.ForeColor = System.Drawing.Color.Red;
subjectCell.CssClass = "emails-table-cell";
fromCell.CssClass = "emails-table-cell";
dateCell.CssClass = "emails-table-cell";
}
else
{
subjectCell.CssClass = "emails-table-cellRead";
fromCell.CssClass = "emails-table-cellRead";
dateCell.CssClass = "emails-table-cellRead";
}
TableRow emailRow = new TableRow();
// emailRow.Cells.Add(noCell);
emailRow.Cells.Add(fromCell);
emailRow.Cells.Add(subjectCell);
emailRow.Cells.Add(dateCell);
//EmailsTable.Rows.Add(emailRow);
EmailsTable.Rows.AddAt(2 + i, emailRow);
}
if (totalPages > 1)
{
if (page > 1)
PreviousPageLiteral.Text = String.Format(SelfLink, page - 1, "Previous Page");
if (page > 0 && page < totalPages)
NextPageLiteral.Text = String.Format(SelfLink, page + 1, "Next Page");
}
EmailFromLiteral.Text = Convert.ToString(((page - 1) * NoOfEmailsPerPage) + 1);
EmailToLiteral.Text = Convert.ToString(page * NoOfEmailsPerPage);
EmailTotalLiteral.Text = Convert.ToString(totalEmails);
EmailLiteral.Text = emailAddress;
}

Dynamically attach entry to context

I am using .Net 4.5 and Entity Framework 6 to create a REST Web API.
In my Update methods I need to attach the object recieved in the web api, back to the dbcontext. I have achieved this using the code below. What I want to do now, is to make this code reusable so that I can call AttachToContext for any object in the model.
I understand that I have to use generic type T and TEntity, but I cannot find any suitable examples.
//Repository.cs
public void UpdateOrderItem(OrderItem orderItem)
{
try
{
AttachToContext(orderItem);
_context.SaveChanges();
}
catch (Exception e)
{
}
}
private void AttachToContext(OrderItem orderItem)
{
var entry = _context.Entry<OrderItem>(orderItem);
if (entry.State == EntityState.Detached)
{
var attachedEntity = FindExistingEntity(orderItem.Id);
if (EntityExists(attachedEntity))
{
UpdateEntityValues(attachedEntity, orderItem);
}
else
{
entry.State = EntityState.Modified;
}
}
}
private OrderItem FindExistingEntity(int id)
{
var set = _context.Set<OrderItem>();
return set.Find(id);
}
private void UpdateEntityValues(OrderItem existing, OrderItem updated)
{
var attachedEntry = _context.Entry(existing);
attachedEntry.CurrentValues.SetValues(updated);
}
private bool EntityExists(object entity)
{
return entity != null;
}
Your AttachToContext has dependency to primary key property, orderItem.Id, to change it into dynamic, you can introduce an interface and implement to all entities you have or just passing the id as parameters.
Interface
public interface IEntity
{
public int Id { get; set; }
}
public class OrderItem : IEntity
{
// body
}
Then modify the AttachToContext as follow.
private void AttachToContext<T>(T entity) where T : class, IEntity
{
var entry = _context.Entry(entity);
if (entry.State == EntityState.Detached)
{
var attachedEntity = FindExistingEntity<T>(entity.Id);
if (EntityExists(attachedEntity))
{
UpdateEntityValues(attachedEntity, entity);
}
else
{
entry.State = EntityState.Modified;
}
}
}
private T FindExistingEntity<T>(int id) where T : class
{
var set = _context.Set<T>();
return set.Find(id);
}
private void UpdateEntityValues<T>(T existing, T updated) where T : class
{
var attachedEntry = _context.Entry(existing);
attachedEntry.CurrentValues.SetValues(updated);
}
The usage would be AttachToContext(orderItem);.
Passing The Keys
private void AttachToContext<T>(T entity, params object[] id) where T : class
{
var entry = _context.Entry(entity);
if (entry.State == EntityState.Detached)
{
var attachedEntity = FindExistingEntity<T>(id);
if (EntityExists(attachedEntity))
{
UpdateEntityValues(attachedEntity, entity);
}
else
{
entry.State = EntityState.Modified;
}
}
}
private T FindExistingEntity<T>(object[] id) where T : class
{
var set = _context.Set<T>();
return set.Find(id);
}
private void UpdateEntityValues<T>(T existing, T updated) where T : class
{
var attachedEntry = _context.Entry(existing);
attachedEntry.CurrentValues.SetValues(updated);
}
The usage would be AttachToContext(orderItem, orderItem.Id);.
Another alternative would be using object set to get the primary key properties, then using reflection to get the value. To get the primary key properties has been explained in this post.

How to generate documentation for Asp.Net MVC?

With .net 4.0/Preview kit 2, we can generate help pages for WCF REST.
Is there anyway we can do the same for MVC ?
www.somewebsite.com/search/help
I can create help pages (views) and expose them.
I can generate XSD schema and spit out as xml.
Any other guidance/suggestions ?
I want to generate something similar to this.
UriTemplate http://somewebsite.com/Search/
Method PUT
Response Format Xml
Response Schema http://somewebsite.com/help/response/schema
Response Example http://somewebsite.com/help/response/example
Update:
I was able to create documentation by using below code.
Route : somewebsite.com/Media/
HelpRoute : somewebsite.com/Media/Help (Append help to the parent route)
Add routes accordingly. See below example.
routes.MapRoute("Search",
"Search/Quick/",
new { controller = "Search", action = "Search" },
new { httpMethod = new HttpMethodConstraint("PUT") }
);
routes.MapRoute("SearchHelp",
"Search/Quick/Help",
new { controller = "Search", action = "Search" },
new { helpConstraint = new HelpConstraint { Help = true, SampleType = typeof(Search) } }
);
public class HelpResult : ViewResult
{
private string HelpPage { get; set; }
private string folderName = "HelpFiles";
private HttpServerUtilityBase server { get; set; }
private Type sampleType { get; set; }
private string schemaName { get; set; }
const string htmlFormat =
#"
<html>
<head>
<title>Help</title>
</head>
<body>
<li>URL - {0}</li>
<li>Verb - {1}</li>
{2}
</body>
</html>
";
public override void ExecuteResult(ControllerContext context)
{
server = context.HttpContext.Server;
StringBuilder parentUrl = new StringBuilder();
var data = context.RouteData.Route.GetRouteData(context.HttpContext);
//Getting requested route url.
string url = ((Route)(data.Route)).Url;
//Getting parent route from requested route url by removing "Help" from the route.
string newUrl = url.Substring(0, url.Length - 4);
parentUrl.Append("/" + newUrl);
sampleType = data.GetSampleType();
var validVerbs = GetValidVerbs(MakeAppRelative(parentUrl.ToString()));
CreateSchema(sampleType, true);
HelpPage = string.Format(htmlFormat, newUrl, validVerbs, CreateInputSampleText());
context.HttpContext.Response.Output.Write(HelpPage);
}
private string CreateInputSampleText()
{
if (sampleType != null && !string.IsNullOrEmpty(sampleType.Name))
{
string sampleText =
#"<li>Input Sample Xml - <a href='\HelpFiles\{0}.xml'>Click Here</a></li>
<li>Input Sample Json - <a href='\HelpFiles\{0}.txt'>Click Here</a></li>
<li>Input Schema - <a href='\HelpFiles\{1}'>Click Here</a></li>";
sampleText = string.Format(sampleText, sampleType.Name, schemaName);
return sampleText;
}
return string.Empty;
}
private static string MakeAppRelative(string url)
{
if (!url.StartsWith("~"))
{
if (!url.StartsWith("/"))
url = "~/" + url;
else
url = "~" + url;
}
return url;
}
private static string GetValidVerbs(string Url)
{
StringBuilder validVerbs = new StringBuilder();
var httpMethodOptions = new[] { "GET", "POST", "PUT", "DELETE", "HEAD" };
foreach (var httpMethodOption in httpMethodOptions)
{
var fakeContext = new FakeHttpContext(MakeAppRelative(Url), httpMethodOption);
foreach (Route route in RouteTable.Routes)
{
var rd = route.GetRouteData(fakeContext);
if (rd != null)
{
bool errorControllerApplied = route.IsErrorController();
if (!errorControllerApplied)
{
validVerbs.Append(httpMethodOption);
}
}
}
}
return validVerbs.ToString();
}
private void CreateFile(Type type, Stream stream)
{
using (Stream inputStream = stream)
{
schemaName = sampleType + "Schema.xml";
string folder = Path.GetFullPath(Path.Combine(server.MapPath("~"), folderName));
string file = Path.Combine(folder, schemaName);
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
using (FileStream fileStream = new FileStream(file, FileMode.Create))
{
byte[] fileContent = new byte[inputStream.Length];
inputStream.Read(fileContent, 0, fileContent.Length);
fileStream.Write(fileContent, 0, fileContent.Length);
fileStream.Flush();
}
}
}
private void CreateSchema(Type type, bool isXmlSerializerType)
{
System.Collections.IEnumerable schemas;
if (isXmlSerializerType)
{
XmlReflectionImporter importer = new XmlReflectionImporter();
XmlTypeMapping typeMapping = importer.ImportTypeMapping(type);
XmlSchemas s = new XmlSchemas();
XmlSchemaExporter exporter = new XmlSchemaExporter(s);
exporter.ExportTypeMapping(typeMapping);
schemas = s.GetSchemas(null);
}
else
{
XsdDataContractExporter exporter = new XsdDataContractExporter();
exporter.Export(type);
schemas = exporter.Schemas.Schemas();
}
using (MemoryStream stream = new MemoryStream())
{
XmlWriterSettings xws = new XmlWriterSettings() { Indent = true };
using (XmlWriter w = XmlWriter.Create(stream, xws))
{
w.WriteStartElement("Schemas");
foreach (XmlSchema schema in schemas)
{
if (schema.TargetNamespace != "http://www.w3.org/2001/XMLSchema")
{
schema.Write(w);
}
}
}
stream.Seek(0, SeekOrigin.Begin);
CreateFile(type, stream);
}
}
public static class RouteDataExtensions
{
public static bool IsHelpConstraintApplied(this RouteData data)
{
if (data != null && data.Route != null)
{
var constraints = ((Route) (data.Route)).Constraints;
var helpConstraint = (from c in constraints.Values
where c.GetType().Equals(typeof (HelpConstraint))
select c).FirstOrDefault();
if (helpConstraint != null)
{
return true;
}
}
return false;
}
public static Type GetSampleType(this RouteData data)
{
if (data != null && data.Route != null)
{
var constraints = ((Route)(data.Route)).Constraints;
var helpConstraint = (from c in constraints.Values
where c.GetType().Equals(typeof(HelpConstraint))
select c).FirstOrDefault();
if (helpConstraint != null)
{
return ((HelpConstraint) helpConstraint).SampleType;
}
}
return null;
}
public static string GetMethodType(this RouteData data)
{
if (data != null && data.Route != null)
{
var constraints = ((Route) (data.Route)).Constraints;
var httpMethodConstraint = (from c in constraints.Values
where c.GetType().Equals(typeof (HttpMethodConstraint))
select c).FirstOrDefault();
if (httpMethodConstraint != null)
{
return ((HttpMethodConstraint) httpMethodConstraint).AllowedMethods.Single();
}
}
return null;
}
public static bool IsErrorController(this Route data)
{
if (data != null)
{
var defaults = ((Route)(data)).Defaults;
var controllerName = (from c in defaults.Values
where c.ToString().Contains("Error")
select c).FirstOrDefault();
if (controllerName != null)
{
return true;
}
}
return false;
}
public static RouteData GetRouteDataByUrl(this string url)
{
string httpMethod = "PUT";
var fakeContext = new FakeHttpContext(MakeAppRelative(url), httpMethod);
return RouteTable.Routes.GetRouteData(fakeContext);
}
private static string MakeAppRelative(string url)
{
if (!url.StartsWith("~"))
{
if (!url.StartsWith("/"))
url = "~/" + url;
else
url = "~" + url;
}
return url;
}
}
public class HelpConstraint : IRouteConstraint
{
public bool Help { get; set; }
public Type SampleType { get; set; }
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if(Help)
{
return true;
}
return false;
}
}
References
http://stephenwalther.com/blog/archive/2008/08/03/asp-net-mvc-tip-29-build-a-controller-to-debug-your-custom-routes.aspx
http://aspnet.codeplex.com/releases/view/24644
This code is not bug free. Please post improvements if you have any. Use it at your own risk.
Not exactly sure what you are looking for, but you can check out GhostDoc:
http://submain.com/products/ghostdoc.aspx
I use this to generate XML documentation in MVC.
Most probably you have solved your issue by now. Anyway, I think you need IApiExplorer. Have a look at this blog.

Anyone have sample code for a UserControl with pager controls to be used in a GridView's PagerTemplate?

I've got several Gridviews in my application in which I use a custom PagerTemplate. I'd like to turn this custom template into a UserControl so that I don't need to replicate the same logic in multiple pages. I'm pretty sure that such a thing is possible, but I'm unsure of how exactly to wire the UserControl to the Gridview's events, and what interfaces my control may need to implement.
I'm using ASP 2.0 frameworks.
Has anyone done something like this? And if so, do you have any sample code for your usercontrol?
Dave Anderson, a co-worker of mine, wrote this server control that could help you get started. Note that we're targeting .NET 3.5.
[AspNetHostingPermission(
SecurityAction.Demand,
Level = AspNetHostingPermissionLevel.Minimal),
AspNetHostingPermission(SecurityAction.InheritanceDemand,
Level = AspNetHostingPermissionLevel.Minimal),
DefaultProperty("Text"),
ToolboxData("<{0}:Pager runat=\"server\"> </{0}:Pager>"),
Designer(typeof(ServerControls.Design.PagerDesigner))
]
public class Pager : WebControl, INamingContainer
{
#region Private Constants
private const string Command_First = "First";
private const string Command_Prev = "Prev";
private const string Command_Next = "Next";
private const string Command_Last = "Last";
#endregion
#region Private members
private Control PageableNamingContainer;
private PropertyInfo PageCountInfo;
private PropertyInfo PageIndexInfo;
private DropDownList ddlCurrentPage;
private Label lblPageCount;
private Button btnFirst;
private Button btnPrevious;
private Button btnNext;
private Button btnLast;
#endregion
#region Private Properties
private int PageCount
{
get
{
int Result;
if (InsideDataPager)
Result = (int)Math.Ceiling((decimal)(TotalRowCount / PageSize)) + 1;
else
Result = (int)PageCountInfo.GetValue(PageableNamingContainer, null);
return Result;
}
}
private int PageIndex
{
get
{
int Result;
if (InsideDataPager)
Result = (int)Math.Floor((decimal)(StartRowIndex / PageSize));
else
Result = (int)PageIndexInfo.GetValue(PageableNamingContainer, null);
return Result;
}
}
private int StartRowIndex
{
get
{
if (InsideDataPager)
return MyDataPager.StartRowIndex;
else
throw new Exception("DataPager functionality requires DataPager.");
}
}
private int TotalRowCount
{
get
{
if (InsideDataPager)
return MyDataPager.TotalRowCount;
else
throw new Exception("DataPager functionality requires DataPager.");
}
}
private int PageSize
{
get
{
if (InsideDataPager)
return MyDataPager.PageSize;
else
throw new Exception("DataPager functionality requires DataPager.");
}
}
private bool InsideDataPager
{
get { return ViewState["InsideDataPager"] == null ? false : (bool)ViewState["InsideDataPager"]; }
set { ViewState["InsideDataPager"] = value; }
}
#region DataPager-Specific properties
private DataPager MyDataPager
{
get
{
if (InsideDataPager)
return (DataPager)PageableNamingContainer;
else
throw new Exception("DataPager functionality requires DataPager.");
}
}
private int PrevPageStartIndex
{
get { return StartRowIndex >= PageSize ? StartRowIndex - PageSize : 0; }
}
private int NextPageStartIndex
{
get { return StartRowIndex + PageSize >= TotalRowCount ? LastPageStartIndex : StartRowIndex + PageSize; }
}
private int LastPageStartIndex
{
get { return (PageCount-1) * PageSize; }
}
#endregion
#endregion
#region Public Properties
[
Category("Behavior"),
DefaultValue(""),
Description("The stylesheet class to use for the buttons")
]
public bool HideInactiveButtons { get; set; }
[
Category("Behavior"),
DefaultValue("true"),
Description("Indicates whether the controls will invoke validation routines")
]
public bool CausesValidation { get; set; }
[
Category("Appearance"),
DefaultValue(""),
Description("The stylesheet class to use for the buttons")
]
public string ButtonCssClass { get; set; }
[
Category("Appearance"),
DefaultValue("<<"),
Description("The text to be shown on the button that navigates to the First page")
]
public string FirstText { get; set; }
[
Category("Appearance"),
DefaultValue("<"),
Description("The text to be shown on the button that navigates to the Previous page")
]
public string PreviousText { get; set; }
[
Category("Appearance"),
DefaultValue(">"),
Description("The text to be shown on the button that navigates to the Next page")
]
public string NextText { get; set; }
[
Category("Appearance"),
DefaultValue(">>"),
Description("The text to be shown on the button that navigates to the Last page")
]
public string LastText { get; set; }
#endregion
#region Overridden properties
public override ControlCollection Controls
{
get
{
EnsureChildControls();
return base.Controls;
}
}
#endregion
#region Overridden methods/events
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!GetPageInfo(NamingContainer))
throw new Exception("Unable to locate the Pageable Container.");
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (PageableNamingContainer != null)
{
EnsureChildControls();
ddlCurrentPage.Items.Clear();
for (int i = 0; i < PageCount; i++)
ddlCurrentPage.Items.Add(new ListItem((i + 1).ToString(), (i + 1).ToString()));
lblPageCount.Text = PageCount.ToString();
if (HideInactiveButtons)
{
btnFirst.Visible = btnPrevious.Visible = (PageIndex > 0);
btnLast.Visible = btnNext.Visible = (PageIndex < (PageCount - 1));
}
else
{
btnFirst.Enabled = btnPrevious.Enabled = (PageIndex > 0);
btnLast.Enabled = btnNext.Enabled = (PageIndex < (PageCount - 1));
}
ddlCurrentPage.SelectedIndex = PageIndex;
}
else
ddlCurrentPage.SelectedIndex = 0;
}
protected override bool OnBubbleEvent(object source, EventArgs args)
{
// We handle all our events inside this class when
// we are inside a DataPager
return InsideDataPager;
}
#endregion
#region Event delegate
protected void PagerEvent(object sender, EventArgs e)
{
if (InsideDataPager)
{
int NewStartingIndex;
if (sender.GetType() == typeof(Button))
{
string arg = ((Button)sender).CommandArgument.ToString();
switch (arg)
{
case Command_Prev:
NewStartingIndex = PrevPageStartIndex;
break;
case Command_Next:
NewStartingIndex = NextPageStartIndex;
break;
case Command_Last:
NewStartingIndex = LastPageStartIndex;
break;
case Command_First:
default:
NewStartingIndex = 0;
break;
}
}
else
{
NewStartingIndex = Math.Min(((DropDownList)sender).SelectedIndex * PageSize, LastPageStartIndex);
}
MyDataPager.SetPageProperties(NewStartingIndex, MyDataPager.MaximumRows, true);
}
else
{
CommandEventArgs ea = new CommandEventArgs("Page", ((DropDownList)sender).SelectedValue);
RaiseBubbleEvent(this, ea);
}
}
#endregion
#region GetPageableContainer
private bool GetPageInfo(Control namingContainer)
{
if (namingContainer == null || namingContainer.GetType() == typeof(Page))
throw new Exception(this.GetType().ToString() + " must be used in a pageable container like a GridView.");
/*
* NOTE: If we are inside a DataPager, this will be
* our first-level NamingContainer, so there
* will never be any reflection in that case.
*/
if (namingContainer.GetType() == typeof(DataPagerFieldItem))
{
InsideDataPager = true;
PageableNamingContainer = ((DataPagerFieldItem)namingContainer).Pager;
return true;
}
PageCountInfo = namingContainer.GetType().GetProperty("PageCount");
PageIndexInfo = namingContainer.GetType().GetProperty("PageIndex");
if (PageCountInfo == null || PageIndexInfo == null)
return GetPageInfo(namingContainer.NamingContainer);
else
{
PageableNamingContainer = namingContainer;
return true;
}
}
#endregion
#region Control generation
protected override void CreateChildControls()
{
Controls.Clear();
Controls.Add(BuildControlTable());
}
private Table BuildControlTable()
{
Table ControlTable = new Table();
ControlTable.CssClass = CssClass;
TableRow tr = new TableRow();
TableCell td = new TableCell();
td.Text = "Page";
tr.Cells.Add(td);
td = new TableCell();
ddlCurrentPage = new DropDownList();
ddlCurrentPage.ID = "ddlCurrentPage";
ddlCurrentPage.AutoPostBack = true;
ddlCurrentPage.SelectedIndexChanged += PagerEvent;
ddlCurrentPage.CausesValidation = CausesValidation;
td.Controls.Add(ddlCurrentPage);
tr.Cells.Add(td);
td = new TableCell();
td.Text = "of";
tr.Cells.Add(td);
td = new TableCell();
lblPageCount = new Label();
td.Controls.Add(lblPageCount);
tr.Cells.Add(td);
AddButton(tr, ref btnFirst, string.IsNullOrEmpty(FirstText) ? "<<" : FirstText, Command_First);
AddButton(tr, ref btnPrevious, string.IsNullOrEmpty(PreviousText) ? "<" : PreviousText, Command_Prev);
AddButton(tr, ref btnNext, string.IsNullOrEmpty(NextText) ? ">" : NextText, Command_Next);
AddButton(tr, ref btnLast, string.IsNullOrEmpty(LastText) ? ">>" : LastText, Command_Last);
ControlTable.Rows.Add(tr);
return ControlTable;
}
private void AddButton(TableRow row, ref Button button, string text, string argument)
{
button = new Button();
button.Text = text;
button.CssClass = ButtonCssClass;
button.CommandName = "Page";
button.CommandArgument = argument;
button.CausesValidation = CausesValidation;
if (InsideDataPager)
button.Click += PagerEvent;
TableCell td = new TableCell();
td.Controls.Add(button);
row.Cells.Add(td);
}
#endregion
}

Resources