Wait operation timeout while uploading through Excel Loader in MVC - asp.net

I'm uploading data from Excel file to database, MVC code reads the first record but on second record it throughs Time Out exception after adding user at "result"
HttpPostedFileBase file = Request.Files["students"];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
string fileName = file.FileName;
string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
}
var studentList = new List<RegisterViewModel>();
using (var package = new ExcelPackage(file.InputStream))
{
var currentSheet = package.Workbook.Worksheets;
var workSheet = currentSheet.First();
var noOfCol = workSheet.Dimension.End.Column;
var noOfRow = workSheet.Dimension.End.Row;
for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
{
var student = new RegisterViewModel();
var Fname = workSheet.Cells[rowIterator, 1].Value.ToString();
var Mname = workSheet.Cells[rowIterator, 2].Value.ToString();
var Lname = workSheet.Cells[rowIterator, 3].Value.ToString();
student.Name = Fname + " " + Mname + " " + Lname;
student.UserName = workSheet.Cells[rowIterator, 4].Value.ToString();
student.Email = workSheet.Cells[rowIterator, 5].Value.ToString();
student.Password = workSheet.Cells[rowIterator, 6].Value.ToString();
student.ConfirmPassword = workSheet.Cells[rowIterator, 7].Value.ToString();
ApplicationDbContext context = new ApplicationDbContext();
var user = new ApplicationUser { UserName = student.UserName, Email = student.Email, Name = student.Name };
var result = await UserManager.CreateAsync(user, student.Password);
if(result!="false")
{

Set executionTimeout property of httpRuntime tah in web.config as shown below:
<system.web>
...
<httpRuntime targetFramework="4.5.1" executionTimeout="30" />
</system.web>
Hope this helps...

Related

How to write two Handlers using Switch Case

i wrote two handlers but i need to write now only one handler using switch case how to write i tried but not working. please help me. this is my two handlers code i want that in switch case.please solve this problem
public void ProcessRequest(HttpContext context)
{
string fname = string.Empty;
string ffname = string.Empty;
string m_Result = string.Empty;
DataTable dt = new DataTable();
Guid id = Guid.NewGuid();
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
ffname = "~/Adds_uploads/" + fname;
}
string p = Path.GetFileNameWithoutExtension(fname);
fname = Path.Combine(context.Server.MapPath("~/Adds_uploads/"), p);
file.SaveAs(fname + id + Path.GetExtension(ffname));
string dirName1 = new DirectoryInfo(fname).Name;
FileInfo fInfo = new FileInfo(ffname);
String dirName = fInfo.Directory.Name + '/' + dirName1 + id + Path.GetExtension(ffname);
HttpContext.Current.Response.Write(JsonConvert.SerializeObject(dirName));
//RAID = context.Request.QueryString["RA_ID"].ToString();
//UploadFileToDB(file, RAID);
}
}
}
public bool IsReusable {
get {
return false;
}
}
2nd Handler
public void ProcessRequest(HttpContext context)
{
string fname = string.Empty;
string ffname = string.Empty;
string m_Result = string.Empty;
DataTable dt = new DataTable();
Guid id = Guid.NewGuid();
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
ffname = "~/Fileuploads/" + fname;
}
string p = Path.GetFileNameWithoutExtension(fname);
fname = Path.Combine(context.Server.MapPath("~/Fileuploads/"), p);
file.SaveAs(fname + id + Path.GetExtension(ffname));
string dirName1 = new DirectoryInfo(fname).Name;
FileInfo fInfo = new FileInfo(ffname);
String dirName = fInfo.Directory.Name + '/' + dirName1 + id + Path.GetExtension(ffname);
HttpContext.Current.Response.Write(JsonConvert.SerializeObject(dirName));
//RAID = context.Request.QueryString["RA_ID"].ToString();
//UploadFileToDB(file, RAID);
}
}
}
public bool IsReusable {
get {
return false;
}
}
I think the only difference if the upload path. I would suggest you to pass along another input form the view and then determine the upload path based on that.
i.e
you would have
//for case one
<input type='hidden' name='uploadType' value='files' />
//for case two
<input type='hidden' name='uploadType' value='adds' />
inside your individual file upload forms and then on your action method you can just use
var mappedDirectory = HttpContext.Current.Request.Form["uploadType"].ToString() == "adds" ? "~/Adds_uploads/" : "~/Fileuploads/";
and use this string in your fname construct. So your new method would be like
public void ProcessRequest(HttpContext context)
{
var mappedDirectory = HttpContext.Current.Request.Form["uploadType"].ToString() == "adds" ? "~/Adds_uploads/" : "~/Fileuploads/";
string fname = string.Empty;
string ffname = string.Empty;
string m_Result = string.Empty;
DataTable dt = new DataTable();
Guid id = Guid.NewGuid();
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
ffname = mappedDirectory + fname;
}
string p = Path.GetFileNameWithoutExtension(fname);
fname = Path.Combine(context.Server.MapPath(mappedDirectory), p);
file.SaveAs(fname + id + Path.GetExtension(ffname));
string dirName1 = new DirectoryInfo(fname).Name;
FileInfo fInfo = new FileInfo(ffname);
String dirName = fInfo.Directory.Name + '/' + dirName1 + id + Path.GetExtension(ffname);
HttpContext.Current.Response.Write(JsonConvert.SerializeObject(dirName));
//RAID = context.Request.QueryString["RA_ID"].ToString();
//UploadFileToDB(file, RAID);
}
}
}

null104Invalid MailChimp "Invalid MailChimp API key: xxxx.."

I am trying this code for creating new campaign using MailChimp API in ASP.NET
public string CreateCampaignAndSend(string apiKey, string listID)
{
Int32 TemplateID = 100;
string campaignID = string.Empty;
MailChimpManager mc = new MailChimpManager("sampleAPIKeyXXXXXXXXXXXXXX-us12");
// compaign Create Options
campaignCreateOptions campaignCreateOpt = new campaignCreateOptions();
campaignCreateOpt.list_id = listID;
campaignCreateOpt.subject = "subject";
campaignCreateOpt.from_email = "wisdomthnkrs#gmail.com";
campaignCreateOpt.from_name = "abc";
campaignCreateOpt.template_id = TemplateID;
campaignCreateOpt.authenticate = true;
campaignCreateOpt.auto_footer = false;
campaignCreateOpt.tracking.opens = true;
campaignCreateOpt.tracking.html_clicks = true;
campaignCreateOpt.tracking.text_clicks = true;
// Content
Dictionary<string, string> content = new Dictionary<string, string>();
content.Add("html_ArticleTitle1", "ArticleTitle1");
content.Add("html_ArticleTitle2", "ArticleTitle2");
content.Add("html_ArticleTitle3", "ArticleTitle3");
content.Add("html_Article1", "Article1");
content.Add("html_Article2", "Article2");
//Conditions
List<campaignSegmentCondition> csCondition = new List<campaignSegmentCondition>();
campaignSegmentCondition csC = new campaignSegmentCondition();
csC.field = "interests-" + 123; // where 123 is the Grouping Id from listInterestGroupings()
csC.op = "all";
csC.value = "";
csCondition.Add(csC);
// Options
campaignSegmentOptions csOptions = new campaignSegmentOptions();
csOptions.match = "all";
// Type Options
Dictionary<string, string> typeOptions = new Dictionary<string, string>();
typeOptions.Add("offset-units", "days");
typeOptions.Add("offset-time", "0");
typeOptions.Add("offset-dir", "after");
// Create Campaigns
campaignCreateParms campaignCreateParms = new campaignCreateParms(mc.APIKey, EnumValues.campaign_type.regular, campaignCreateOpt, content, csOptions, typeOptions);
campaignCreateInput campCreateInput = new campaignCreateInput(campaignCreateParms);
campaignCreate campaignCreate = new campaignCreate(campCreateInput);
//xyz();
//string abc = xxxxxxxxxxxxxxxxx;
campaignCreateOutput ccOutput = campaignCreate.Execute(campCreateInput);
List<Api_Error> error = ccOutput.api_ErrorMessages; // Catching API Errors
string s = "null";
if (error.Count <= 0)
{
campaignID = ccOutput.result;
}
else
{
foreach (Api_Error ae in error)
{
Console.WriteLine("\n ERROR Creating Campaign : ERRORCODE\t:" + ae.code + "\t ERROR\t:" + ae.error);
s = s + ae.code;
s = s + ae.error;
}
}
return s;
}
but it shows an error while I am giving the right key.
here is the error,
null104Invalid MailChimp "Invalid MailChimp API key:
6ea29f158xxxxxxxxxxxx"

Issues on converting the java code to c#

I tried to convert java code into cSharp .I struct on how to encode the data so please help me how to do that..
I tried to pass the values directly without encoding then i got the error as
The remote server returned an error: (400) Bad Request.
if i removed the headers then the error is not coming and i placed the break point in the web site the execution sequence is not stopped at the break point
this is my java code
packagename=encodeData("some value");
username=encodeData("some value");
password=encodeData("some value");
hc= new DefaultHttpClient();
get= new HttpGet("http://techpalle.com/skillgun_App.svc/mobile/papers/"+chap_id+"/app");
get.setHeader(PaperActivity.this.getString(R.string.username),username);
get.setHeader(PaperActivity.this.getString(R.string.password),password);
get.setHeader(PaperActivity.this.getString(R.string.packagename),packagename);
Converted csharp code is
string username=null;
string password=null;
string packagename=null;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://localhost:2850/TechpalleNew/Skillgun_App.svc/mobile/chapters/" + "16" + "/app");
wr.Headers["username"] = "username";
wr.Headers["password"] = "password";
wr.Headers["packagename"] = "packagename";
WebResponse resp = wr.GetResponse();
StreamReader read = new StreamReader(resp.GetResponseStream());
string res = read.ReadToEnd();
My website code
namespace ISkillgun_App
{
[ServiceContract]
public interface ISkillgun_App
{
[OperationContract]
[System.ServiceModel.Web.WebInvoke(Method = "GET", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json, BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped, UriTemplate = "mobile/chapters/{sub_topic_id}/app")]
List<ChapterNames> Chapters_Names(string sub_topic_id);
[OperationContract]
[System.ServiceModel.Web.WebInvoke(Method = "GET", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json, BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped, UriTemplate = "mobile/papers/{chapter_id}/app")]
List<Paper_Ids> Paper_ids(string chapter_id);
[OperationContract]
[System.ServiceModel.Web.WebInvoke(Method = "GET", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json, BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped, UriTemplate = "mobile/questions/{paper_id}/app")]
List<Qtions_data> Qtions_data(string paper_id);
}
}
namespace Skillgun_App:ISkillgun_App
{
public List<ChapterNames> Chapters_Names(string sub_topic_id)
Breakppoint {
List<ChapterNames> chptrsdetails = new List<ChapterNames>();
using (SqlConnection cn = new SqlConnection(strConnection))
{
using (SqlCommand cmd = new SqlCommand("skillgun_mobile_app_Qtions_data", cn))
{
cmd.CommandType = CommandType.StoredProcedure;
try
{
SqlParameter p1 = new SqlParameter("#type", SqlDbType.VarChar, 20);
SqlParameter p2 = new SqlParameter("#topic_or_paper_id", SqlDbType.Int);
p1.Value = "chapters_data";
p2.Value = sub_topic_id;
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add("#username", SqlDbType.VarChar, 40);
cmd.Parameters["#username"].Direction = ParameterDirection.Output;
cmd.Parameters.Add("#password", SqlDbType.VarChar, 40);
cmd.Parameters["#password"].Direction = ParameterDirection.Output;
cmd.Parameters.Add("#package_name", SqlDbType.VarChar, 50);
cmd.Parameters["#package_name"].Direction = ParameterDirection.Output;
cn.Open();
SqlDataReader drtopics = cmd.ExecuteReader();
while (drtopics.Read())
{
ChapterNames qbsubchapter = new ChapterNames();
qbsubchapter.Qbc_id = (int)drtopics["qbc_id"];
qbsubchapter.Qbc_nameofChapter = drtopics["qbc_nameofChapter"].ToString();
qbsubchapter.Qbc_no_of_papers = (int)drtopics["qbc_no_of_papers"];
qbsubchapter.Qbc_no_of_questions = (int)drtopics["qbc_no_of_questions"];
chptrsdetails.Add(qbsubchapter);
}
drtopics.Close();
cn.Close();
string topic_username = cmd.Parameters["#username"].Value.ToString();
string topic_password = cmd.Parameters["#password"].Value.ToString();
string topic_package_name = cmd.Parameters["#package_name"].Value.ToString();
bool result = check_user(topic_username, topic_password, topic_package_name);
if (result == true)
return chptrsdetails;
else
return null;
}
catch (SqlException ex)
{
return null;
}
finally
{
if (cn.State == ConnectionState.Open)
{
cn.Close();
}
}
}
}
}
public bool check_user(string topic_username, string topic_password, string topic_package_name)
{
string requestedUrl = OperationContext.Current.IncomingMessageHeaders.To.AbsoluteUri;
if (WebOperationContext.Current != null)
{
if (WebOperationContext.Current.IncomingRequest != null)
{
if (WebOperationContext.Current.IncomingRequest.Headers["username"] != null && WebOperationContext.Current.IncomingRequest.Headers["password"] != null && WebOperationContext.Current.IncomingRequest.Headers["packagename"] != null)
{
string username = WebOperationContext.Current.IncomingRequest.Headers["username"];
string pwd = WebOperationContext.Current.IncomingRequest.Headers["password"];
string pckgname = WebOperationContext.Current.IncomingRequest.Headers["packagename"];
bool result = Base64Decode(username, pwd, pckgname, topic_username, topic_password, topic_package_name);
if (result == true)
return true;
else
return false;
}
}
}
return false;
}
For html encoding (you don't specify other), use the static method
HttpUtility.HtmlEncode(string)
http://www.dotnetperls.com/httputility

facebook graph api version "2.4 "could not access email,gender information in the "me" tag

my sample project at registered at developer.facebook version 2.4 and requested permissions are *
email,birthday,gender
*
default.aspx
string code = Request.QueryString["code"];
if (!string.IsNullOrEmpty(code))
{
// dynamic info = fb.Get("me?birthday");
string data = FaceBookConnect.Fetch(code, "me");
FaceBookUser faceBookUser = new JavaScriptSerializer().Deserialize<FaceBookUser>(data);
faceBookUser.PictureUrl = string.Format("https://graph.facebook.com/{0}/picture", faceBookUser.Id);
pnlFaceBookUser.Visible = true;
lblId.Text = faceBookUser.Id;
lblUserName.Text = faceBookUser.UserName;
lblName.Text = faceBookUser.Name;
lblEmail.Text = faceBookUser.Email;
lblbirthday.Text = faceBookUser.birthday;
lblf_name.Text =faceBookUser.first_name;
lblgender.Text = faceBookUser.gender;
ProfileImage.ImageUrl = faceBookUser.PictureUrl;
btnLogin.Enabled = false;
}

Unable to pass parameters to SSRS report in ASP.NET page

Hi I am getting an error in supplying parameters to an SSRS report deployed on server in ASP.NET page.
Please refer to the code below and let me know where is the issue?
ReportExecutionService rs = new ReportExecutionService();
string rptURL = System.Configuration.ConfigurationManager.AppSettings["rptURL"].ToString();
string rptPath = System.Configuration.ConfigurationManager.AppSettings["Page1SLScorecardReortForDownload"].ToString();
//Microsoft.Reporting.WebForms.ReportParameter[] paramlist = new Microsoft.Reporting.WebForms.ReportParameter[3];
//paramlist[0] = new Microsoft.Reporting.WebForms.ReportParameter("Week", "2013-05-03");
//paramlist[1] = new Microsoft.Reporting.WebForms.ReportParameter("year", "Fiscal Calendar 2013");
//paramlist[2] = new Microsoft.Reporting.WebForms.ReportParameter("Month", "Fiscal May, 2013");
ParameterValue[] paramlist = new ParameterValue[3];
//Microsoft.Reporting.WebForms.ReportParameter[] paramlist = new Microsoft.Reporting.WebForms.ReportParameter[3];
paramlist[0] = new ParameterValue();
paramlist[0].Name = "Week";
paramlist[0].Value = "2013-05-03";
paramlist[1] = new ParameterValue();
paramlist[1].Name = "year";
paramlist[1].Value = "Fiscal Calendar 2013";
paramlist[2] = new ParameterValue();
paramlist[2].Name = "Month";
paramlist[2].Value = "Fiscal May, 2013";
//ReportViewer1.ServerReport.SetParameters(paramlist);
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = rptURL;
byte[] result = null;
string reportPath = rptPath;
string format = "EXCEL";
string historyID = null;
string devInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
string encoding;
string mimeType;
string extension;
ReportingWS.Warning[] warnings = null;
string[] streamIDs = null;
ReportingWS.ExecutionInfo execInfo = new ReportingWS.ExecutionInfo();
ReportingWS.ExecutionHeader execHeader = new ReportingWS.ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportPath, historyID);
rs.SetExecutionParameters(paramlist, "en-us");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
try
{
result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
execInfo = rs.GetExecutionInfo();
}
catch (Exception ex)
{
//AlnErrorHandler.HandleError(ex);
}
parameters.Add(new ReportParameter("FyId", Convert.ToInt16(objSession.FyId).ToString()));
parameters.Add(new ReportParameter("AccountGroupId", cmbAccountGroup.SelectedValue));
parameters.Add(new ReportParameter("LedgerId", cmbLedgerId.SelectedValue));
rptvwMain.ServerReport.SetParameters(parameters);
Pass Parameters like this....

Resources