How to Resolve DNN Custom Module Not Rendering? - c#

I'm using DNN 9.3.2 and Chris Hammond's module template to create a custom module. When I load the module onto a page without visibility restrictions, it does not render. The Event Log does not contain any errors after installation or rendering of said page.
Since this is my first DNN MVC module, I'm thinking this has to do with the following controller class I've created:
[DnnHandleError]
public class SignupController : DnnController
{
// GET: Signup
[ModuleAction(ControlKey = "Edit", TitleKey = "AddItem")]
public ActionResult Index()
{
var signups = OnboardingManager.Instance.GetOnboardings(ModuleContext.ModuleId);
return View(signups);
}
[HttpPost]
[DotNetNuke.Web.Mvc.Framework.ActionFilters.ValidateAntiForgeryToken]
public ActionResult Edit(Models.Onboarding onboarding)
{
ProPayService service = new ProPayService();
OnboardingManager.Instance.CreateOnboarding(onboarding);
service.MerchantSignupForProPayAsync();
return RedirectToDefaultRoute();
}
public ActionResult Edit(int onboardingId = -1)
{
DotNetNuke.Framework.JavaScriptLibraries.JavaScript.RequestRegistration(CommonJs.DnnPlugins);
var userlist = UserController.GetUsers(PortalSettings.PortalId);
var users = from user in userlist.Cast<UserInfo>().ToList()
select new SelectListItem { Text = user.DisplayName, Value = user.UserID.ToString() };
ViewBag.Users = users;
var onboarding = (onboardingId == -1) ? new Models.Onboarding{ModuleId = ModuleContext.ModuleId} : OnboardingManager.Instance.GetOnboarding(onboardingId, ModuleContext.ModuleId);
return View(onboarding);
}
}
The service class referenced above is defined as follows:
public class ProPayService
{
private static HttpClient _httpClient = new HttpClient();
//private readonly string _baseUrl = "https://xmltestapi.propay.com/ProPayAPI";
Uri _baseUrl = new Uri("https://xmltestapi/propay.com/ProPayAPI");
public ProPayResponse MerchantSignupForProPayAsync()
{
SignupRequest signupRequest = new SignupRequest();
SignupResponse signupResponse = new SignupResponse();
HttpContent content = new StringContent(signupRequest.ToString());
CancellationToken cancellationToken = new CancellationToken();
var credentials = GetCredentials();
var responseBody = _httpClient.PutAsync(_baseUrl, content, cancellationToken).Result;
try
{
BuildMerchantTestData();
Console.WriteLine(responseBody);
Console.WriteLine(content);
if (WebRequest.Create(_baseUrl) is HttpWebRequest httpRequest)
{
httpRequest.Method = "PUT";
httpRequest.Headers.Add("accept", "applicaiton/json");
httpRequest.Headers.Add("Authorization", credentials);
}
//var httpRequest = new HttpRequestMessage(HttpMethod.Put, _baseUrl);
//httpRequest.Headers.Add("Authorization", credentials);
Console.WriteLine(signupResponse.Status);
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException caught");
Console.WriteLine("Message: {0} ", e.Message);
}
return JsonConvert.DeserializeObject<ProPayResponse>(responseBody.Content.ReadAsStringAsync().Result);
}
private SignupRequest BuildMerchantTestData()
{
int moduleId = 0;
int OnboardingId = 0;
var result = OnboardingManager.Instance.GetOnboarding(OnboardingId, moduleId);
var onboardingList = new List<Models.Onboarding>();
var ownerList = new List<OwnerList>();
SignupRequest signupRequest = new SignupRequest();
if (result != null)
{
Debug.Assert(result != null, nameof(OnboardingList) + " != null");
Console.WriteLine("{0} {1}", result.Email, result.UserId);
List<Owner> owner1 = new List<Owner>
{
new Owner
{
FirstName = result.OwnerFirstName,
LastName = result.OwnerLastName,
Address = result.OwnerAddress,
City = result.OwnerCity,
State = result.OwnerRegion,
Zip = result.OwnerZipCode,
Country = result.OwnerCountry,
DateOfBirth = result.OwnerDob,
SSN = result.OwnerSsn,
Email = result.Email,
Percentage = result.OwnerPercentage,
Title = result.OwnerTitle
}
};
signupRequest = new SignupRequest
{
PersonalData = new PersonalData
{
FirstName = result.FirstName,
MiddleInitial = result.MiddleInitial,
LastName = result.Lastname,
DateOfBirth = result.DateOfBirth,
SocialSecurityNumber = result.Ssn,
SourceEmail = result.Email,
PhoneInformation =
new PhoneInformation
{ DayPhone = result.DayPhone, EveningPhone = result.EveningPhone },
},
InternationalSignUpData = null,
//InternationalSignUpData = new InternationalSignupData
//{
// DocumentExpDateString = result.DocumentExpDate,
// DocumentIssuingState = result.DocumentIssuingState,
// DocumentType = result.DocumentType,
// DriversLicenseVersion = result.DriversLicenseVersion,
// InternationalId = result.InternationalId,
// MedicareCardColor = result.MedicareCardColor,
// MedicareReferenceNumber = result.MedicareReferenceNumber
//},
NotificationEmail = result.Email,
SignupAccountData = new SignupAccountData
{
CurrencyCode = "USD",
//UserId = result.UserId.ToString(),
//PhonePIN = result.PhonePin,
//ExternalId = "12345",
Tier = "Test"
},
BusinessData =
new BusinessData
{
BusinessLegalName = result.BusinessLegalName,
DoingBusinessAs = result.DoingBusinessAs,
EIN = result.Ein,
MerchantCategoryCode = result.MerchantCategoryCode,
WebsiteURL = result.BusinessUrl,
BusinessDescription = result.BusinessDescription,
MonthlyBankCardVolume = result.MonthlyBankCardVolume ?? 0,
AverageTicket = result.AverageTicket ?? 0,
HighestTicket = result.HighestTicket ?? 0
},
Address = new Address
{
ApartmentNumber = result.Address1ApartmentNumber,
Address1 = result.Address1Line1,
Address2 = result.Address1Line1,
City = result.Address1City,
State = result.Address1State,
Country = result.Address1Country,
Zip = result.Address1ZipCode
},
MailAddress = new Address
{
ApartmentNumber = result.OwnerApartmentNumber,
Address1 = result.OwnerAddress,
Address2 = result.OwnerAddress2,
City = result.OwnerCity,
State = result.OwnerRegion,
Country = result.OwnerCountry,
Zip = result.OwnerZipCode
},
BusinessAddress =
new Address
{
ApartmentNumber = result.BusinessApartmentNumber,
Address1 = result.BusinessAddressLine1,
Address2 = result.BusinessAddressLine2,
City = result.BusinessCity,
State = result.BusinessState,
Country = result.BusinessCountry,
Zip = result.BusinessZipCode
},
//CreditCardData = new CreditCardData
//{
// NameOnCard = result.NameOnCard,
// CreditCardNumber = result.CreditCardNumber, // test card number
// ExpirationDate = result.ExpirationDate
//},
BankAccount =
new BankAccount
{
AccountCountryCode = result.BankAccount1CountryCode,
BankAccountNumber = result.BankAccount1Number,
RoutingNumber = result.BankAccount1RoutingNumber,
AccountOwnershipType = result.BankAccount1OwnershipType,
BankName = result.BankAccount1BankName,
AccountType = "Checking",
//AccountType = result.BankAccount1Type,
AccountName = result.BankAccount1Name,
Description = result.BankAccount1Description
},
//SecondaryBankAccount =
// new BankAccount
// {
// AccountCountryCode = result.BankAccount2CountryCode,
// BankAccountNumber = result.BankAccount2Number,
// RoutingNumber = result.BankAccount2RoutingNumber,
// AccountOwnershipType = result.BankAccount2OwnershipType,
// BankName = result.BankAccount2BankName,
// AccountType = result.BankAccount2Type,
// AccountName = result.BankAccount2Name,
// Description = result.BankAccount2Description
// },
//GrossBillingInformation = new GrossBillingInformation
//{
// GrossSettleAddress = new Address
// {
// Address1 = result.OwnerAddress,
// Address2 = result.OwnerAddress2,
// ApartmentNumber = result.OwnerApartmentNumber,
// City = result.OwnerCity,
// Country = result.OwnerCountry,
// State = result.OwnerRegion,
// Zip = result.OwnerZipCode
// },
// GrossSettleBankAccount = new BankAccount
// {
// AccountCountryCode = "USA",
// AccountName = result.BankAccount1Name,
// AccountOwnershipType = result.BankAccount1OwnershipType,
// AccountType = result.BankAccount1Type,
// BankAccountNumber = result.BankAccount1Number,
// BankName = result.BankAccount1BankName,
// Description = result.BankAccount1Description,
// RoutingNumber = result.BankAccount1RoutingNumber
// },
// GrossSettleCardData = new CreditCardData
// {
// CreditCardNumber = result.CreditCardNumber,
// ExpirationDate = result.ExpirationDate,
// NameOnCard = result.NameOnCard
// }
//},
//FraudDetectionData = new FraudDetectionData
//{
// MerchantSourceIp = result.MerchantSourceIp,
// ThreatMetrixPolicy = result.ThreatMetrixPolicy,
// ThreatMetrixSessionId = result.SessionId
//},
//PaymentMethodId = result.PaymentMethodId,
//PaymentBank = new BankAccount
//{
// AccountName = result.PaymentBankAccountName,
// AccountCountryCode = result.PaymentBankCountryCode,
// AccountOwnershipType = result.PaymentBankOwnershipType,
// AccountType = result.PaymentBankAccountType,
// BankAccountNumber = result.PaymentBankAccountNumber,
// BankName = result.PaymentBankName,
// Description = result.PaymentBankAccountDescription,
// RoutingNumber = result.PaymentBankRoutingNumber
//}
BeneficialOwnerData = new BeneficialOwnerData
{
OwnerCount = "1",
Owners = owner1
}
};
Console.WriteLine(JsonConvert.SerializeObject(signupRequest));
}
//return new SignUpRequest();
return signupRequest;
}
private static string GetCredentials()
{
var termId = "myId"; // put affiliate term id here, if you have it
var certString = "myCert"; // put affiliate cert string here
var encodedCredentials = Convert.ToBase64String(Encoding.Default.GetBytes(certString + ":" + termId));
var credentials = $"Basic {encodedCredentials}";
return credentials;
}
}
The DNN manifest file is defined as follows:
<dotnetnuke type="Package" version="5.0">
<packages>
<package name="Onboarding" type="Module" version="00.00.01">
<friendlyName>Onboarding</friendlyName>
<description>Onboarding</description>
<iconFile>~/Icons/Sigma/Software_32X32_Standard.png</iconFile>
<owner>
<name>SocialBodega.com</name>
<organization>SocialBodega.com</organization>
<url>https://www.socialbodega.com/</url>
<email>info#socialbodega.com</email>
</owner>
<license src="License.txt"></license>
<releaseNotes src="ReleaseNotes.txt"></releaseNotes>
<dependencies>
<dependency type="CoreVersion">08.00.00</dependency>
</dependencies>
<components>
<component type="Script">
<scripts>
<basePath>DesktopModules\MVC\Onboarding</basePath>
<script type="Install">
<path>Providers\DataProviders\SqlDataProvider</path>
<name>00.00.01.SqlDataProvider</name>
<version>00.00.01</version>
</script>
<script type="UnInstall">
<path>Providers\DataProviders\SqlDataProvider</path>
<name>Uninstall.SqlDataProvider</name>
<version>00.00.01</version>
</script>
</scripts>
</component>
<component type="ResourceFile">
<resourceFiles>
<basePath>DesktopModules/MVC/Onboarding</basePath>
<resourceFile>
<name>Resources.zip</name>
</resourceFile>
</resourceFiles>
</component>
<component type="Module">
<desktopModule>
<moduleName>Onboarding</moduleName>
<foldername>Onboarding</foldername>
<businessControllerClass>SocialBodega.Onboarding.Components.FeatureController</businessControllerClass>
<supportedFeatures />
<moduleDefinitions>
<moduleDefinition>
<friendlyName>Onboarding</friendlyName>
<defaultCacheTime>0</defaultCacheTime>
<moduleControls>
<!--<moduleControl>
<controlKey />
<controlSrc>SocialBodega.Onboarding.Controllers/Item/Index.mvc</controlSrc>
<supportsPartialRendering>False</supportsPartialRendering>
<controlTitle />
<controlType>View</controlType>
<iconFile />
<helpUrl />
<viewOrder>0</viewOrder>
</moduleControl>-->
<moduleControl>
<controlKey/>
<controlSrc>SocialBodega.Onboarding.Controllers/Signup/Index.mvc</controlSrc>
<supportPartialRendering>False</supportPartialRendering>
<controlTitle/>
<controlType>View</controlType>
<iconFile/>
<helpUrl/>
<viewOrder>0</viewOrder>
<supportsPopUps>True</supportsPopUps>
</moduleControl>
<moduleControl>
<controlKey>Edit</controlKey>
<controlSrc>SocialBodega.Onboarding.Controllers/Signup/Edit.mvc</controlSrc>
<supportsPartialRendering>False</supportsPartialRendering>
<controlTitle>Edit Signups</controlTitle>
<controlType>Edit</controlType>
<iconFile />
<helpUrl />
<viewOrder>0</viewOrder>
<supportsPopUps>True</supportsPopUps>
</moduleControl>
<moduleControl>
<controlKey>Settings</controlKey>
<controlSrc>SocialBodega.Onboarding.Controllers/Settings/Settings.mvc</controlSrc>
<supportsPartialRendering>False</supportsPartialRendering>
<controlTitle>Onboarding Settings</controlTitle>
<controlType>Edit</controlType>
<iconFile />
<helpUrl />
<viewOrder>0</viewOrder>
</moduleControl>
</moduleControls>
</moduleDefinition>
</moduleDefinitions>
</desktopModule>
</component>
<component type="Assembly">
<assemblies>
<assembly>
<name>Onboarding.dll</name>
<path>bin</path>
</assembly>
</assemblies>
</component>
</components>
</package>
</packages>
</dotnetnuke>
Are there changes I should make to my above controller to ensure that the module renders properly? Or are there other items I should review to further diagnose the issue?
Update:
After making a change to the DNN manifest as per comment, I am now unable to add the module to the page and receive the following in admin log:
AbsoluteURL:
DefaultDataProvider:DotNetNuke.Data.SqlDataProvider, DotNetNuke
ExceptionGUID:e229902b-051f-459e-9647-28adcd0d4f50
AssemblyVersion:
PortalId:-1
UserId:-1
TabId:-1
RawUrl:
Referrer:
UserAgent:
ExceptionHash:OLQuqVQLbGm0IndDqnMOfMf2C3Q=
Message:Error Creating BusinessControllerClass
'SocialBodega.Onboarding.Components.FeatureController, SocialBodega.Onboarding' of module(Onboarding) id=(422) in tab(41) and portal(0)
StackTrace:
at DotNetNuke.Services.Search.ModuleIndexer.ThrowLogError(ModuleInfo module,
Exception ex)
InnerMessage:Value cannot be null. Parameter name: type
InnerStackTrace:
at System.Activator.CreateInstance(Type type, Boolean nonPublic) at
System.Activator.CreateInstance(Type type) at
DotNetNuke.Services.Search.ModuleIndexer.GetModuleList(Int32 portalId)
Source:DotNetNuke
My revised DNN Manifest is listed below:
<dotnetnuke type="Package" version="5.0">
<packages>
<package name="Onboarding" type="Module" version="00.00.01">
<friendlyName>Onboarding</friendlyName>
<description>Onboarding</description>
<iconFile>~/Icons/Sigma/Software_32X32_Standard.png</iconFile>
<owner>
<name>SocialBodega.com</name>
<organization>SocialBodega.com</organization>
<url>https://www.socialbodega.com/</url>
<email>info#socialbodega.com</email>
</owner>
<license src="License.txt"></license>
<releaseNotes src="ReleaseNotes.txt"></releaseNotes>
<dependencies>
<dependency type="CoreVersion">08.00.00</dependency>
</dependencies>
<components>
<component type="Script">
<scripts>
<basePath>DesktopModules\MVC\Onboarding</basePath>
<script type="Install">
<path>Providers\DataProviders\SqlDataProvider</path>
<name>00.00.01.SqlDataProvider</name>
<version>00.00.01</version>
</script>
<script type="UnInstall">
<path>Providers\DataProviders\SqlDataProvider</path>
<name>Uninstall.SqlDataProvider</name>
<version>00.00.01</version>
</script>
</scripts>
</component>
<component type="ResourceFile">
<resourceFiles>
<basePath>DesktopModules/MVC/Onboarding</basePath>
<resourceFile>
<name>Resources.zip</name>
</resourceFile>
</resourceFiles>
</component>
<component type="Module">
<desktopModule>
<moduleName>Onboarding</moduleName>
<foldername>Onboarding</foldername>
<businessControllerClass>SocialBodega.Onboarding.
Components.FeatureController,
SocialBodega.Onboarding</businessControllerClass>
<supportedFeatures />
<moduleDefinitions>
<moduleDefinition>
<friendlyName>Onboarding</friendlyName>
<defaultCacheTime>0</defaultCacheTime>
<moduleControls>
<!--<moduleControl>
<controlKey />
<controlSrc>SocialBodega.Onboarding.Controllers/Item/Index.mvc
</controlSrc>
<supportsPartialRendering>False</supportsPartialRendering>
<controlTitle />
<controlType>View</controlType>
<iconFile />
<helpUrl />
<viewOrder>0</viewOrder>
</moduleControl>-->
<moduleControl>
<controlKey/>
<controlSrc>SocialBodega.Onboarding.Controllers/Signup/Index.mvc
</controlSrc>
<supportPartialRendering>False</supportPartialRendering>
<controlTitle/>
<controlType>View</controlType>
<iconFile/>
<helpUrl/>
<viewOrder>0</viewOrder>
<supportsPopUps>True</supportsPopUps>
</moduleControl>
<moduleControl>
<controlKey>Edit</controlKey>
<controlSrc>SocialBodega.Onboarding.Controllers/Signup/Edit.mvc
</controlSrc>
<supportsPartialRendering>False</supportsPartialRendering>
<controlTitle>Edit Signups</controlTitle>
<controlType>Edit</controlType>
<iconFile />
<helpUrl />
<viewOrder>0</viewOrder>
<supportsPopUps>True</supportsPopUps>
</moduleControl>
<moduleControl>
<controlKey>Settings</controlKey>
<controlSrc>SocialBodega.Onboarding.Controllers/Settings/Settings.mvc
</controlSrc>
<supportsPartialRendering>False</supportsPartialRendering>
<controlTitle>Onboarding Settings</controlTitle>
<controlType>Edit</controlType>
<iconFile />
<helpUrl />
<viewOrder>0</viewOrder>
</moduleControl>
</moduleControls>
</moduleDefinition>
</moduleDefinitions>
</desktopModule>
</component>
<component type="Assembly">
<assemblies>
<assembly>
<name>Onboarding.dll</name>
<path>bin</path>
</assembly>
</assemblies>
</component>
</components>
</package>
Update2
I upgraded to DNN 9.4 late last week and took the advice received to comment out all code in my view and just render a label. This worked!! Thus, my view syntax is as per below:
#inherits
DotNetNuke.Web.Mvc.Framework.DnnWebViewPage
<DotNetNuke.Collections.PagedList<SocialBodega.Onboarding.
Models.Onboarding>>
#using System.Linq
#using System.Text.RegularExpressions
#using DotNetNuke.Collections
#using DotNetNuke.Entities.Urls
#using DotNetNuke.Web.Mvc.Helpers
<div id="Onboarding-#Dnn.ModuleContext.ModuleId">
#if (Model == null|| !Model.Any())
{
<p>#Dnn.LocalizeString("NoSignups")</p>
}
else
{
<ul>
#foreach (var onboarding in Model)
{
<li>
<h3>#onboarding.FirstName</h3>
<div>#onboarding.OnboardingId</div>
#{
if (Dnn.ModuleContext.IsEditable)
{
<div>
#Dnn.LocalizeString("EditItem")
</div>
}
}
</li>
}
</ul>
}
</div>
#*#Html.Label("Testing 123");*#
When I build the solution, it succeeds but I do receive 16 error messages in Visual Studio 2019 to the effect of:
Error CS0012 The type 'WebViewPage<>' is defined in an assembly that is
not referenced. You must add a reference to assembly 'System.Web.Mvc,
Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
1_desktopmodules_mvc_onboarding_Views_Signup_Index.cshtml
C:\websites\dnndev.me\DesktopModules\Onboarding\Views\Signup\Index.cshtml
I've added said assembly to web.config in the Views folder of the module and also to the main DNN web.config at C:\websites.dnndev.me using the following:
<compilation debug="true" targetFramework="4.7.2">
<assemblies>
<add assembly="System.Web.Mvc, Version = 5.1.0.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35"/>
<add assembly ="netstandard, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = cc7b13ffcd2ddd51"/>
</assemblies>
</compilation>
How do I prevent the errors from being thrown and ensure that my view renders as desired?

First, be sure your module is compiling against the correct version of .NET Framework that your DNN instance is targeting. You can look for a line in your web.config file, similar to this one:
<compilation debug="false" strict="false" targetFramework="4.5">
In recent versions of DNN, you'll need to be sure to explicitly tell DNN that permissions that your controller is meant to be responding to. Take note of the DnnModuleAuthorize class decoration in the sample below.
using System;
using System.Web.Mvc;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Web.Mvc.Framework.ActionFilters;
namespace SocialBodega.Onboarding.Controllers
{
[DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.View)]
[DnnHandleError]
public class SignupController : DnnBaseController
{
// GET: Signup
[ModuleAction(ControlKey = "Edit", TitleKey = "AddItem")]
public ActionResult Index()
{
var signups = OnboardingManager.Instance.GetOnboardings(ModuleContext.ModuleId);
return View(signups);
}
}
}

Related

how can i display uploaded image from a folder in razor pages

I have a folder which stores attachments of different types with specified prefix.
For example,the image attachment will have "IM-" prefix and document attachment will have "DOC" prefix.
What i need is i want to display the Image attachment only in view page.
How i can get ImageFileName in OnGet method. Here is my Code,
Biodata.cshtml.cs
//--------------------Image Upload ---------------//
[BindProperty]
public IFormFile StaffPhoto { get; set; }
public string ImageName { get; set; }
public async Task OnGetAsync(int? StaffID)
{
StaffGender = new SelectList(_context.Gender, "StaffGender", "StaffGender");
StaffReligion = new SelectList(_context.Religion, "StaffReligion", "StaffReligion");
StaffBioData = await _context.StaffBioData.FirstOrDefaultAsync(m => m.StaffID == StaffID);
DirectoryInfo di = new DirectoryInfo(Path.Combine(_env.WebRootPath, "Documents/OnBoardingAttachments", StaffBioData.EmpID.ToString()));
}
public async Task<IActionResult> OnPostUpdateBioDataAsync(StaffBioData StaffBioData)
{
StaffGender = new SelectList(_context.Gender, "StaffGender", "StaffGender");
StaffReligion = new SelectList(_context.Religion, "StaffReligion", "StaffReligion");
if (!ModelState.IsValid)
{
return Page();
}
else
{
var biodata = from u in _context.StaffBioData select u;
biodata = biodata.Where(s => s.StaffID.Equals(StaffBioData.StaffID));
StaffIDExists = biodata.AsNoTracking().FirstOrDefault();
_context.Entry(StaffBioData).State = StaffIDExists == null?
EntityState.Added :
EntityState.Modified;
await _context.SaveChangesAsync();
var filesave = Path.Combine(_env.WebRootPath, "Documents/OnBoardingAttachments", StaffBioData.EmpID, "IM-" + StaffBioData.EmpID + StaffPhoto.FileName);
using (var stream = System.IO.File.Create(filesave))
{
await StaffPhoto.CopyToAsync(stream);
//TempData["Success"] = "Success";
ImageName = "IM-" + StaffBioData.EmpID + StaffPhoto.FileName;
}
return new OkResult();
}
}
Biodata.cshtml
<!-- Photo -->
<div class="form-group">
<label class="control-label-staff"><b>Photo</b></label>
<span>
<br />
<img src="~/Documents/OnBoardingAttachments/#Request.Query["EmpID"].ToString()/#Model.ImageName" />
</span>
<input type="file" asp-for="StaffPhoto" class="form-control-staff" accept="image/*" style="border:1px solid white;margin-right:20px" />
</div>
Whats happening now is in the edit screen im not getting the value for #Model.ImageName
My folder will have other files also,but i need to display only the file with prefix "IM-"
Any help would be appreciated
For how to display only file with prefix IM-,please check the following code:
public async Task OnGetAsync(int? StaffID)
{
StaffGender = new SelectList(_context.Gender, "StaffGender", "StaffGender");
StaffReligion = new SelectList(_context.Religion, "StaffReligion", "StaffReligion");
StaffBioData = await _context.StaffBioData.FirstOrDefaultAsync(m => m.StaffID == StaffID);
var filePath = Directory.GetFiles(Path.Combine(_env.WebRootPath, "Documents/OnBoardingAttachments", StaffBioData.EmpID.ToString()));
foreach(var path in filePath)
{
var name = Path.GetFileName(path);
if(name.StartsWith("IM-"))
{
ImageName = name;
}
}
}
Result:

Passing parameter to asmx web-service in Postman

I have created a asmx web-service like below:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void GetEmployeesJSONByID(int sId)
{
try {
string sResult = string.Empty;
List<Employee> lstEmp = new List<Employee>();
List<Employee> lstEmpNew = new List<Employee>();
lstEmp.Add(new Employee { Id = 101, Name = "Nitin", Salary = 10000 });
lstEmp.Add(new Employee { Id = 102, Name = "Dinesh", Salary = 20000 });
switch (sId) {
case 101:
lstEmpNew.Add(new Employee { Id = 101, Name = "Nitin", Salary = 10000 });
break;
case 102:
lstEmpNew.Add(new Employee { Id = 102, Name = "Dinesh", Salary = 20000 });
break;
default:
break;
}
JavaScriptSerializer js = new JavaScriptSerializer();
sResult = js.Serialize(lstEmpNew);
Context.Response.Write(sResult);
} catch (Exception ex) {
Context.Response.Write(ex.Message.ToString());
}
}
I want to test this web-service via Postman. So I deployed in my local IIS and in the postman like below:
In the URL I given as
http://XXXXXX/SampleWebService/Service.asmx/GetEmployeesJSONByID?sId=101
I am getting the Request Format is invalid. How to pass this sId in the postman to test this webservice?
Add the following to the <system.web> block in Web.config file:
<webServices>
<protocols>
<add name="HttpGet" />
<add name="HttpPost" />
</protocols>
</webServices>
Well the error image in the question has the request method as POST in Postman and the Source code has UseHttpGet = true for the WebMethod.

Paypal payment is not redirecting to the right url in MVC .Net

Currenty I am implementing a third party payment system through paypal in my MVC application. I have created the payment details are getting through, but at the start of the method when checking if the user is logged in or not (currently the user is not logged in) the redirection link rel is not being appruval_url but it is giving self. Below is the code that I currently have.
This code is set in a controller being called by a button.
//Controller code
// Paypal Payment
private Payment payment;
// Create a payment using APIContext
private Payment CreatePayment(APIContext apiContext, string redirectUrl)
{
var listItems = new ItemList() { items = new List<Item>() };
listItems.items.Add(new Item()
{
name = "M&Ms",
currency = "EUR",
price = "0.7",
quantity = "5",
sku = "sku"
});
var payer = new Payer() { payment_method = "paypal" };
var redirUrls = new RedirectUrls()
{
cancel_url = redirectUrl,
return_url = redirectUrl
};
// Create detials object
var details = new Details()
{
tax = "0",
shipping = "0",
subtotal = "3.5"
};
// Create amount object
var amount = new Amount()
{
currency = "EUR",
total = "3.5",
details = details
};
var transectionList = new List<Transaction>();
transectionList.Add(new Transaction()
{
description = "Testing transection",
invoice_number = Convert.ToString((new Random().Next(100000))),
amount = amount,
item_list = listItems
});
payment = new Payment()
{
intent = "sale",
payer = payer,
transactions = transectionList,
redirect_urls = redirUrls
};
return payment.Create(apiContext);
}
// Create Execute Payment method
private Payment ExecutePayment(APIContext apiContext, string payerid, string paymentId)
{
var paymentExecution = new PaymentExecution()
{
payer_id = payerid
};
payment = new Payment() { id = paymentId };
return payment.Execute(apiContext, paymentExecution);
}
// Create Payment with Paypal
public ActionResult PaymentWithPaypal()
{
APIContext apiContext = PaypalConfiguration.GetAPIContext();
try
{
string payerId = Request.Params["PayerID"];
if (string.IsNullOrEmpty(payerId))
{
// Creating payment
string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Orders/Index.aspx?";
var guid = Convert.ToString((new Random()).Next(100000));
var createdPayment = CreatePayment(apiContext, baseURI + "guid=" + guid);
// Gets links returned from Paypal response to create call function
var links = createdPayment.links.GetEnumerator();
string paypalRedirectUrl = string.Empty;
while (links.MoveNext())
{
Links link = links.Current;
var temp = link.rel.ToLower().Trim();
if (link.rel.ToLower().Trim().Equals("appruval_url"))
{
paypalRedirectUrl = link.href;
}
Session.Add(guid, createdPayment.id);
return Redirect(paypalRedirectUrl);
}
}
else
{
var guid = Request.Params["guid"];
var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
if (executedPayment.state.ToLower() != "approved")
{
return View("Failure");
}
}
}
catch (Exception e)
{
PaypalLogger.Log("Error: " + e.Message);
return View("Failure");
}
return View("Success");
}
// webconfig code
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit
http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- Paypal & Log4net -->
<section name="paypal" type="PayPal.SDKConfigHandler, PayPal" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<!-- PayPal SDK settings -->
<paypal>
<settings>
<add name="mode" value="sandbox" />
<add name="connectionTimeout" value="360000" />
<add name="requestRetries" value="1" />
<add name="clientId" value="AdzOKk5M7yVA_dWjifjTs6rSAZX9pCRJ7xJ5wX4e_TikEPieiGBJwuMz8h4Su0UVpPVIB5IMgghc7XvZ" />
<add name="clientSecret" value="EEmh_b6MxGLxNNjbI4E-eW96MluwGd0TxU_Ex8Rehyk4yoeHWfiRaS4ERlAVfFrq_izauhIWZukhJ8At" />
</settings>
</paypal>

LargeJsonResult in MVC return many values

I have a controller which return many datas. then i got "Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property."
i have add my web.config using this. But the error is still occured.
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483645" recursionLimit="100">
</jsonSerialization>
</webServices>
</scripting>
</system.web.extensions>
then I add new class LargeJsonResult like on this website http://brianreiter.org/2011/01/03/custom-jsonresult-class-for-asp-net-mvc-to-avoid-maxjsonlength-exceeded-exception/
it said like this in controller
return new LargeJsonResult() { Data = output, MaxJsonLength = int.MaxValue };
but how can I use that with many return data? below is my controller
public ActionResult LoadInitData()
{
try
{
Database db = new Database("CON001");
_employee = Helper.Common.GetEmployeeData(db);
EmployeeDAC dacEmployee = new EmployeeDAC(db);
Employee dataEmployee = dacEmployee.GetDataByComputerLogin(GetUser());
if (_employee.SBU == "FB")
{
BrandBudgetDAC dacBrandBudget = new BrandBudgetDAC(db);
List<BrandBudget> dataBrandBudget = dacBrandBudget.GetDataBrandFB();
PostBudgetDAC dacPostBudget = new PostBudgetDAC(db);
List<PostBudget> dataPostBudget = dacPostBudget.GetDataPostFB();
AreaDAC dacArea = new AreaDAC(db);
List<Area> dataArea = dacArea.GetData();
return Json(new { Employee = dataEmployee, BrandBudget = dataBrandBudget, PostBudget = dataPostBudget, Area = dataArea }, JsonRequestBehavior.AllowGet);
}
else
{
BrandBudgetDAC dacBrandBudget = new BrandBudgetDAC(db);
List<BrandBudget> dataBrandBudget = dacBrandBudget.GetData(_employee.SBU);
PostBudgetDAC dacPostBudget = new PostBudgetDAC(db);
List<PostBudget> dataPostBudget = dacPostBudget.GetData(_employee.SBU);
AreaDAC dacArea = new AreaDAC(db);
List<Area> dataArea = dacArea.GetData();
return Json(new { Employee = dataEmployee, BrandBudget = dataBrandBudget, PostBudget = dataPostBudget, Area = dataArea }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return Json(new { Error = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
To reduce the payload, consider making 4 separate ajax calls, each to a different method that returns one of the 4 properties you need.
public ActionResult LoadInitEmployeeData()
{
Employee dataEmployee = ....
....
return Json(dataEmployee, JsonRequestBehavior.AllowGet)
}
public ActionResult LoadBrandBudgetData()
{
List<BrandBudget> dataBrandBudget = ....
return Json(dataBrandBudget, JsonRequestBehavior.AllowGet)
}
etc.

Trying to read web.config file for an IIS site from a Windows service

I am trying to look for a special web.config file for a web site installed on a local IIS. I do this search from a Windows service. I do the following:
using (ServerManager serverManager = new ServerManager())
{
for (int r = 0; r < serverManager.Sites.Count; r++)
{
string strSiteName = serverManager.Sites[r].Name;
ApplicationCollection arrApps = serverManager.Sites[r].Applications;
for (int a = 0; a < arrApps.Count; a++)
{
Microsoft.Web.Administration.Application aa = arrApps[a];
foreach (VirtualDirectory vd2 in aa.VirtualDirectories)
{
string strPhysPath = Environment.ExpandEnvironmentVariables(vd2.PhysicalPath);
int rr = 0;
try
{
Configuration cnfg = serverManager.GetWebConfiguration(strSiteName, strPhysPath);
if (cnfg != null)
{
string swww = getWebConfigGeneralParamValue(cnfg, "SpecNodeName");
}
}
catch
{
//Error
}
}
}
}
Where,
public static string getWebConfigGeneralParamValue(Configuration config, string strParamKey)
{
string strRes = null;
try
{
ConfigurationSection configSection1 = config.GetSection("configuration");
if (configSection1 != null)
{
ConfigurationElement configGeneralParams = configSection1.GetChildElement("GeneralParams");
if (configGeneralParams != null)
{
ConfigurationElementCollection configCol = configSection1.GetCollection();
if (configCol != null)
{
strRes = configCol[strParamKey].ToString();
}
}
}
}
catch(Exception ex)
{
strRes = null;
}
return strRes;
}
and the web.config file that should be recognized by this script is something like this:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<!-- regular ASP.NET config stuff -->
<GeneralParams>
<param key="SpecNodeName" value="Special Node Value"/>
</GeneralParams>
</configuration>
But what I get is that config.GetSection("configuration"); throws this exception:
{"Filename:
\\?\C:\inetpub\wwwroot\C:\Users\Dev\Desktop\CSharp\MyTestWebApp\MyTestWebApp\web.config\r\nError:
The configuration section 'configuration' cannot be read because it is
missing a section declaration\r\n\r\n"}
Any idea how to make it work?
You need not to target configuration, you need to target that particular node from where you need to get your data. here is the example.
using(ServerManager mgr = ServerManager.OpenRemote("Some-Server")) {
Configuration config = mgr.GetWebConfiguration("site-name", "/test-application");
ConfigurationSection appSettingsSection = config.GetSection("appSettings");
ConfigurationElementCollection appSettingsCollection = appSettingsSection.GetCollection();
ConfigurationElement addElement = appSettingsCollection.CreateElement("add");
addElement["key"] = #"NewSetting1";
addElement["value"] = #"SomeValue";
appSettingsCollection.Add(addElement);
serverManager.CommitChanges();
}
I am feeling, if you have web.config why you want to use ServerManager.
Take a look at below code, this I have been using in my code and it works as a charm.
What it does is it loads web.config in readable format.
var assemblyPath = Path.GetDirectoryName(typeof (ConfigurationTests).Assembly.Location);
string webConfigPath = MyPath;
string directory = System.IO.Path.GetFullPath(Path.Combine(assemblyPath,webConfigPath));
Console.WriteLine(directory);
Assert.That(Directory.Exists(directory));
VirtualDirectoryMapping vdm = new VirtualDirectoryMapping(directory, true);
WebConfigurationFileMap wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);
System.Configuration.Configuration webConfig = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
var connectionString = webConfig.ConnectionStrings.ConnectionStrings["ConnectionString"].ConnectionString;
Console.WriteLine("Connection String:");
Console.WriteLine(connectionString);
Console.WriteLine("AppSettings:");
foreach (var key in webConfig.AppSettings.Settings.AllKeys)
{
Console.WriteLine("{0} : {1}", key, webConfig.AppSettings.Settings[key].Value);
}

Categories